Python course / Advanced
Context managers
Put anything inside a with block that is guaranteed to be tidied up afterwards. Cleanup that only runs when nothing goes wrong is the bug you meet during an outage.
- __enter__ and __exit__
- contextlib
- suppressing
- ExitStack
- temporary changes
- all or nothing
Runs in your browser. Start straight away; create an account when you want your progress kept.
from contextlib import contextmanager
@contextmanager
def announced(name):
print("start", name)
try:
yield {"name": name}
finally:
print("finish", name)
with announced("delivery") as job:
print("working on", job["name"])
try:
with announced("unpacking"):
raise ValueError("a crate was empty")
except ValueError as failure:
print("handled:", failure)
start delivery working on delivery finish delivery start unpacking finish unpacking handled: a crate was empty
What you will learn
- Know the two methods behind every with statement, and write a class that works with it.
- Suppress exactly the exceptions you mean to from __exit__, and spot a manager that suppresses everything.
- Write a context manager as a generator with contextlib.contextmanager, cleanup included.
- Reach for suppress, closing and redirect_stdout instead of writing your own.
- Manage several resources in one with, in the right order, including a number only known at run time.
- Make a block's changes take effect only if the whole block succeeds.
The lessons in this module
- What with actually does
- What as names, and what __exit__ is told
- Swallowing exceptions, on purpose or by accident
- Context managers from generators
- The standard library's context managers
- Several at once, and ExitStack
- Changing something temporarily
- A timer you can put around anything
- Used once, used again, used inside itself
- All or nothing
- Capstone: a batch that survives its failures
- Module review: stock in batches
Ready when you are
Previous: Decorators. Next: Dataclasses and the data model. All modules are on the course page.