Context Manager Decorator

Python
Author

Imad Dabbura

Published

December 29, 2022

Instead of creating a class to implement the context manager protocol (__enter__ & __exit__), we can use @contextmanager Decorator from contextlib library to decorate any generator function with a single yield statement. This done by wrapping the function in a class that implements the __enter__ and __exit__ methods.

def gen():
    # Anything here for the setup
    print("setup")

    # expression after yield will be returned after calling the gen 
    # function in `with` block; otherwise, `None` will be returned
    # equivalent to `__enter__`
    yield

    # Anything here will be part of the teardown when we exit the 
    # `with` block, equivalent to `__exit__`
    print("teardown")

with gen():
    print("inside `with` block")
print("outside `with` block")

# Output
setutp
inside `with` block
teardown
outside `with` block

Here is how generator functions decorated with contextmanager get evaluated: