Advanced · 14 min
Context managers
Set up and clean up resources reliably with with.
Guarantee cleanup
A context manager runs entry and exit behavior around a with block, even when the block raises an exception.
class Session:
def __enter__(self):
print("Open")
return self
def __exit__(self, exc_type, exc, traceback):
print("Close")
with Session():
print("Use")Output
Open Use Close
Create one with a generator
contextlib.contextmanager turns a generator with one yield into a context manager. Code after yield performs cleanup.
from contextlib import contextmanager
@contextmanager
def timer():
print("Begin")
yield
print("End")
with timer():
print("Run")Output
Begin Run End
Context managers
- Read both context managers examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Manage a status
Complete active_status so it displays Active before the with block and Inactive after it. Keep the supplied block.
Put setup before yield and cleanup after yield.