Context managers
Pair setup and cleanup with a with block.
A context manager defines what happens when a with block begins and ends. Python runs cleanup even if the block exits with an exception. Opening files with with uses this pattern to close them.
Build a simple manager with contextlib.contextmanager. Set up before yield, yield the value the block receives, and put cleanup in a finally block. The generator must yield exactly once for each use.
Setup runs before control reaches the with block.
Try it yourself
Use a workspace called draft. Inside the with block, raise ValueError. Catch it outside the block and print Recovered. Check the order of the three lines.
Target output
Open draft
Close draft
RecoveredShow a hint
Wrap the whole with statement in try and use except ValueError below it.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
from contextlib import contextmanager
@contextmanager
def workspace(name):
print(f"Open {name}")
try:
yield name
finally:
print(f"Close {name}")
try:
with workspace("draft"):
raise ValueError("Invalid draft")
except ValueError:
print("Recovered")