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.
- 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.
- 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.
__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
__enter__method, then setup is considered invalid and
__exit__is not called
__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.
Below is a sample if how resources (file descriptors, database connections etc ) for an operation can be cleaned without having to wrap it in a
Create multiple patches inside a singular context