Leave the workbench clean.
Pair setup with cleanup so failures do not leak resources.
01 The idea
A context manager defines the work to do when entering and leaving a with block. contextlib.contextmanager lets you describe that pair with a generator that yields once. Put cleanup in finally so it runs when the caller finishes normally or raises an exception. This pattern is useful for files, temporary directories, database resources, and application-level scopes.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from contextlib import contextmanager
@contextmanager
def session(name):
print(f"open {name}")
try:
yield {"name": name}
finally:
print(f"close {name}")
with session("Orbit") as current:
print(current["name"])open Orbit Orbit close Orbit
03 Under the hood
- 1
Entering the with block advances the generator to yield. The yielded value becomes current.
- 2
Leaving resumes the generator, which executes finally. An exception inside the block is delivered back at the yield point.
- 3
Do not swallow an exception accidentally. Catch only failures the manager can intentionally handle; otherwise let them propagate after cleanup. A context manager controls resource lifetime, not automatic transactional correctness.
04 Your turn, builder
Create a scope that appends "opened" and "closed" to a list even when its body raises ValueError.
Reveal one possible solution +
from contextlib import contextmanager
steps = []
@contextmanager
def scope():
steps.append("opened")
try:
yield
finally:
steps.append("closed")
try:
with scope():
raise ValueError("practice")
except ValueError:
pass
print(steps)05 Check your signal
Where should unconditional cleanup live?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.