Context Manager Using @contextmanager Decorator
Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.
@decorator def function(args): statements(s)
A decorated line: Pooventhiran
In this example, whenever print_name() is called, first, msg_decorator is called with print_name as the argument. Inside msg_decorator, msg_wrapper is returned which simply calls whichever function passed to msg_decorator with the arguments passed to it. Though this example is simple, these are so powerful in actual usecases like checking for boundary/special conditions, pre-processing, etc.
Note: For more information refer to Decorators in Python.
Context Managers are Python’s resource managers. In most cases, we use files as resources (a simple resource). We often don’t care about closing the files at the end of execution. This is a bad coding practice and also this causes issues when too many files are opened, or when the program is terminated with failure as the resource is not properly released. Context managers are the rescue for this issue by automatically managing resources. In Python, the with keyword is used.
In the example shown above, the file used is managed by ContextManager itself as it closes the file even if the program fails. This context manager feature can also be built into our programs. The user need to ensure that the class has the methods: __enter__() and __exit__(). Let’s look at a template with these special methods.
init method called enter method called with statement block exit method called
In the above code, __enter__ will be executed when control enters with and __exit__, when control leaves with clause. We can simply make any function as a context manager with the help of contextlib.contextmanager decorator without having to write a separate class or __enter__ and __exit__ functions.
We have to use contextlib.contextmanager to decorate a generator function which yields exactly once. Everything before yield is considered to be __enter__ section and everything after, to be __exit__ section. The generator function should yield the resource.
Example: Let’s rewrite the above example with this decorator
Enter method called with statement block Exit method called
Please Login to comment...