MemotivaContext managers and the with statement

How do you create a context manager using contextlib?

Context managers and the with statement

Audio flashcard · 0:17

Nortren·

How do you create a context manager using contextlib?

0:17

The contextlib.contextmanager decorator turns a generator function into a context manager. The function should yield exactly once. Code before the yield is the setup, code after is the cleanup. Wrap the yield in a try-finally to ensure cleanup runs even if an exception occurs in the with block.
docs.python.org