PYTHON ADVANCEDChapter 9 · Python Advanced
Context managers
A context manager sets something up and guarantees it gets cleaned up, even if an error happens halfway through. with open(...) as f: closes the file for you. Write your own with a class that has __enter__ and __exit__, or more simply with @contextmanager from contextlib around a generator: the code before yield is setup, and the code after it is cleanup.
Worked example
How it reads
- Everything before
yieldruns when thewithblock starts - The yielded value becomes the name after
as finallymakes sure the cleanup runs even if the block raises

Cloud tip: Reach for a context manager whenever something must be undone: closing files, releasing locks, restoring settings.


