Calmcode - context managers: decorator

Building a context manager from scratch.

1 2 3 4 5 6

Below is the initial context manager that we started with.

class PrintingContextManager:
    def __enter__(self):
        print('entering the context manager')
        return "i am the returned value"

    def __exit__(self, exc_type, exc_value, traceback):
        print('exiting the context manager')


with PrintingContextManager() as var:
    print('inside the context manager')
    print(var)

We can choose to rewrite this context manager in a more consise way though by using a generator and a decorator.

from contextlib import contextmanager

@contextmanager
def printing_context_manager():
    print('entering the context manager')
    yield "i am the returned value"
    print('exiting the context manager')


with printing_context_manager() as var:
    print('inside the context manager')
    print(var)

Effectively everything that occurs before the yield statement can be seen as the code that would run in __enter__ beforehand and the code that would run after could be seen as the __exit__ before. In general this functional take is seen as a simpler method of implementing context managers, but it's good to know that you can pick either if you're interested.