Module 17 · Advanced Python Concepts — topic 10 of 14
Context managers
Writing your own context managers: the __enter__/__exit__ protocol, handling exceptions in __exit__, contextlib.contextmanager, and handy standard managers such as suppress and redirect_stdout.
Learning objectives
- Write class-based context managers
- Write generator-based managers with contextlib
- Use standard managers from contextlib
Definition
A context manager is an object that defines setup and cleanup for a with block through __enter__ and __exit__. contextlib.contextmanager lets a generator function act as one: code before yield is setup and code after it is cleanup.
Introduction
Files close themselves in a with block because they are context managers. You can give your own code the same guarantee: temporary settings, timers, transactions.
Why it matters
Context managers make 'always clean up' structural rather than something each caller must remember.
Detailed explanation
with obj as name: calls obj.__enter__() and binds its return value to name.
When the block ends, obj.__exit__(exc_type, exc, tb) runs. The arguments are None if no exception happened.
If __exit__ returns a true value, the exception is suppressed; returning False or None lets it propagate.
@contextlib.contextmanager turns a generator into a manager. Put cleanup in finally to make it run even on errors; catching the exception around yield lets you handle or suppress it.
contextlib.suppress(Error) ignores specific exceptions; redirect_stdout(buffer) captures printed output; ExitStack manages a variable number of managers.
Typical custom managers: temporarily changing state (indentation, directory, settings), timing blocks, and transactions that roll back on failure.
Keep __enter__ and __exit__ short; complex work belongs in normal methods.
A manager can be reused for many with blocks if it resets its state on entry, but generator-based managers are single-use: create a new one for each with statement.
Syntax
- __enter__ sets up, __exit__ cleans up.
- Return True from __exit__ to suppress.
- contextmanager for simple cases.
Code examples
A temporary indentation level
start
step 1
detail
step 2
endStandard helpers
buffer has: captured! KeyError suppressed
More examples
A transaction that rolls back
committed
{'A': 70, 'B': 80}
rolled back: insufficient funds in A
{'A': 70, 'B': 80}Step-by-step explanation
- A snapshot is taken before the block runs.
- If the block raises, the generator catches the exception at yield, restores the snapshot and does not re-raise, so the error is handled.
- On success the else branch reports the commit and the changes stay.
Expected output
Running “A transaction that rolls back” prints exactly:
Practical applications
- Database transactions with sqlite3 connections.
- Temporarily changing settings in tests.
Best practices
- Use finally for cleanup in generator managers.
- Suppress exceptions only deliberately.
- Prefer contextlib helpers over custom code.
Common mistakes
Cleanup without finally
Avoid
Prefer
An exception in the block stops the generator at yield.
Important notes
- Async code uses async with and __aenter__/__aexit__.
Key takeaways
- __enter__/__exit__ define a context manager.
- contextmanager turns generators into managers.
- suppress, redirect_stdout and ExitStack are ready-made.
Try it yourself
- 1Write a context manager that changes the working directory and restores it afterwards.
- 2Write a timer context manager that stores the elapsed time on the object.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?
- AdvancedWhat is printed?