Context Managers & Resource Protocols
Master __enter__/__exit__ mechanics, contextlib internals, ExitStack, async context managers, and exception suppression edge cases.
How Context Managers & Resource Protocols behaves during execution
Context managers manage setup and teardown lifecycles around code blocks using the with statement. In CPython, context managers implement the __enter__ and __exit__ dunder methods. They guarantee that system resources—such as open file descriptors, database connections, and synchronization locks—are safely closed or released even when exceptions are raised inside the wrapped block.
Upon entering a with block, CPython invokes __enter__() and binds its return value to the optional 'as' target. Upon exiting the block (normally or via exception), __exit__(exc_type, exc_val, exc_tb) is executed. If an exception occurred and __exit__ returns a truthy value, CPython suppresses the exception and execution resumes normally; if it returns falsy, the exception is re-raised.
A frequent bug when writing custom context managers is returning True unconditionally from __exit__. This inadvertently swallows ALL exceptions—including SyntaxError, KeyboardInterrupt, and NameError—hiding critical bugs and making debugging nearly impossible. __exit__ should only suppress specific, anticipated exception types.
How to use this tool
Read the server-rendered examples above first, write down each variable change in a trace table, then use the interactive workspace below to step through execution. Tracing builds clear mental models for technical interviews.
Worked example
# Trace the execution line by line x = 10 y = x * 2 print(x + y)
Static result: 30
Controls
The code panel shows the snippet; Run executes it in the browser Pyodide sandbox; Next and Previous step through line states; the result panel displays output and state changes.
Honest limits
Python code executes locally inside your browser WebAssembly (Pyodide) sandbox. Execution is client-side, rate-free, and isolated from our servers. Do not enter credentials or private API keys.
Continue with the Python Mastery Hub.
Interactive Dry-Run Execution Workspace
__enter__ Return Value Binding
Trace CPython execution step-by-step and deduce the exact stdout string emitted by this snippet.
class Ctx:
def __enter__(self): return 'bound'
def __exit__(self, *a): pass
with Ctx() as val:
print(val)Frequently Asked Questions on Context Managers & Resource Protocols
How does returning True from __exit__ affect exception propagation?
If an exception is raised inside a with block and __exit__ returns True (or a truthy value), CPython suppresses the exception. The exception is swallowed and program execution continues on the line following the with statement.
How does the contextlib.contextmanager generator decorator work?
The @contextmanager decorator transforms a generator into a context manager. Code before the yield statement runs during __enter__(), the yielded value binds to the 'as' target, and code after the yield (typically in a finally block) executes during __exit__().
Can multiple context managers be combined in a single with statement?
Yes. In Python 3, multiple context managers can be chained separated by commas: with open('a.txt') as fa, open('b.txt') as fb:. They enter in left-to-right order and exit in reverse (right-to-left) order.