Writing your own contextmanager using generator syntax
suggest changeIt is also possible to write a context manager using generator syntax thanks to the contextlib.contextmanager decorator:
import contextlib
@contextlib.contextmanager
def context_manager(num):
print('Enter')
yield num + 1
print('Exit')
with context_manager(2) as cm:
# the following instructions are run when the 'yield' point of the context
# manager is reached.
# 'cm' will have the value that was yielded
print('Right in the middle with cm = {}'.format(cm))
produces:
Enter
Right in the middle with cm = 3
Exit
The decorator simplifies the task of writing a context manager by converting a generator into one. Everything before the yield runs as __enter__, the yielded value is what __enter__ returns (and what as binds), and everything after the yield runs as __exit__.
An exception from the with block is thrown into the generator at the yield. An except there can catch it; if it does not re-raise, the exception is suppressed. finally still runs. Code after the yield does not run unless it is in that finally, or the exception was caught.
@contextlib.contextmanager
def error_handling_context_manager(num):
print("Enter")
try:
yield num + 1
except ZeroDivisionError:
print("Caught error")
finally:
print("Cleaning up")
print("Exit")
with error_handling_context_manager(-1) as cm:
print("Dividing by cm = {}".format(cm))
print(2 / cm)
This produces:
Enter
Dividing by cm = 0
Caught error
Cleaning up
Exit
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents