Context managers are inherent feature of python to provide a way to obtain and release resources on demand. When a context manager is used, a definite scope is defined to safely delete or clean resources. For example a file can be read in below two ways.

  1. In this method, python interpreter has no way to estimate the need for myFile in future. Hence it holds on to the file descriptor until the program scope.
  2. This method of file access ensures a clear scope of the usage of the resource file test.txt. This file is closed at the end of the block, and any file descriptor associated is released. This cleanup is performed behind the scenes as an effect of opening he file in a context.
To achieve such behavior a class must define below two methods.
  1. __enter__: called at the time of entering the context, allocates resources

    • Return value shall be the handle to the object we want to pass for further operation within the block.
    • Most common is to to return self here.
    • If an Exception is raise on the __init__ or the __enter__ method, then setup is considered invalid and __exit__ is not called
  2. __exit__: called while exiting the context, cleans up resources.

    • It is called on the original class
    • Can suppress errors by returning True
Example usage of context managers.
  1. Exception Flow:

    Below is a sample if how resources (file descriptors, database connections etc ) for an operation can be cleaned without having to wrap it in atry..except..finally block.

  2. Bundled Patches:

    Create multiple patches inside a singular context

Categories: Python

Naved

An adept programmer with experience in design, development and deployment of multiple application routines. Knowledge of various software designs paradigms, development frameworks, deployment methodologies, database modelling and process migration. Special focus on business driven design, search optimization, user interface, data access and data storage implementation. A hacker with a penchant for making technological processes more readily and comprehensively accessible.