Context Managers in Python
Chapter 28: Context Managers
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
with: always clean up
with something as name: sets something up, runs the block, and always cleans up at the end, even if the block raises an error.
Writing a context manager: __enter__ and __exit__
Any class becomes a context manager by having enter (runs on the way in; its return value goes after as) and exit (runs on the way out, always).
@contextmanager: a context manager from a generator
@contextmanager turns a generator into a context manager: the code before yield is the setup, the yielded value goes after as, and the code after yield is the clean-up.
Handy context managers, and several at once
contextlib.suppress(Error) quietly ignores one expected error inside its block, and one with can open several managers at once, cleaning them up in reverse order.