Python Context Managers: Async, ExitStack, Custom
A context manager is a promise that setup and teardown stay together, and the details of that promise are where the interesting behaviour lives. __exit__ receives the exception that ended the block and can choose to suppress it; a generator-based manager built with @contextmanager must yield exactly once; several resources acquired in a loop need ExitStack; and asynchronous code needs the same guarantees under async with. Each of these has a failure mode that only shows up under error conditions â which is precisely when guarantees matter. This lesson covers the contract first, then the four ways to implement it and when each is the right choice.
What You'll Learn
- 1Explain the __enter__ and __exit__ contract including exception suppression
- 2Write @contextmanager functions that behave correctly on every exit path
- 3Group dynamic resource sets with ExitStack
- 4Build and consume async context managers safely
The contract, including the parts nobody reads
Entering a with statement calls __enter__ and binds its return value to the as target; leaving the block calls __exit__, even when an exception is propagating. __exit__ receives three arguments â exception type, value, and traceback â all None on a clean exit, and its return value decides whether the exception continues: a falsy return lets it propagate, a truthy return suppresses it entirely, as though the block never raised.
Suppression is powerful and rarely what you want by default, which is why most implementations end with return False or fall off the end. The legitimate uses are narrow: a manager that provides a fallback, records an error and continues, or translates the exception into a result the caller expects. Returning True from a manager that does not handle the failure destroys evidence â the exception vanishes, and the program continues in a state that was never validated.
class Traced:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"enter {self.name}")
return self
def __exit__(self, exc_type, exc_value, tb):
print(f"exit {self.name} type={exc_type.__name__ if exc_type else None}")
return False # never suppress
class Suppressing:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
return exc_type is not None # swallow, but only real exceptions
with Traced("block"):
print("body")
try:
with Suppressing("quiet"):
raise ValueError("hidden")
except ValueError:
print("still visible")
else:
print("suppressed â nothing reached the caller")
The contrast is the lesson: the first manager observes and lets the exception continue, the second swallows it. Read every third-party manager's __exit__ before relying on it, because suppression is invisible in the signature.
Generator managers, written defensively
contextlib.contextmanager turns a generator into a context manager: code before the yield runs on entry, the yield value becomes the as target, and code after it runs on exit. It is concise enough to reach for by default, and it has three sharp edges. The generator must yield exactly once â a second yield raises RuntimeError. Code after the yield must not swallow an exception the caller still expects, and contextmanager deliberately re-raises exceptions thrown into the generator rather than letting you silently ignore them.
The robust shape is a try around the yield with a finally for unconditional cleanup, and an except only when you intend to translate or handle. Be careful about catching broadly: if you catch and do not re-raise, the caller's exception disappears. When cleanup itself can fail, decide which error wins â typically the original exception should propagate and the cleanup failure should be logged.
from contextlib import contextmanager
import time
@contextmanager
def timed(label, log):
start = time.perf_counter()
try:
yield start
except Exception as err:
log.append(f"{label} failed: {err}")
raise # translate nothing, swallow nothing
finally:
log.append(f"{label} took {time.perf_counter() - start:.6f}s")
@contextmanager
def open_maybe(path, encoding="utf-8"):
handle = open(path, encoding=encoding)
try:
yield handle
except OSError as err:
print(f"read problem: {err}")
raise
finally:
handle.close()
audit = []
with timed("work", audit):
with open_maybe("does-not-exist.txt") as handle:
handle.read()
print(audit[0]) # work failed: ...
print(audit[1].startswith("work took")) # True â finally still ran
Note that the finally runs even when the body raised â that ordering is what makes the pattern safe. What the pattern does not give you is control over suppression; if you need __exit__ semantics precisely, use a class.
ExitStack for resources you cannot count in advance
When the number of resources depends on data â opening every file in a list, acquiring a lock per shard â nesting with statements is impossible, and a fixed tuple of contexts is too rigid. contextlib.ExitStack accepts any number of enter_context calls and unwinds them in reverse order on exit, exactly as nested with blocks would have. Reverse ordering matters: resources acquired later depend on earlier ones, so release must run last-in-first-out.
ExitStack also handles mixed types: files, locks, patches, and temporary directories can share one stack, and callback lets you register a plain function for cleanup that has no __enter__ at all. The failure mode to avoid is entering a context that fails mid-way â ExitStack still unwinds everything already entered, which is the correct behaviour and the reason it beats a hand-written loop of acquires.
from contextlib import ExitStack, callback
import tempfile
import os
def process_all(paths, log):
with ExitStack() as stack:
handles = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
stack.callback(log.append, "released all handles")
return [len(h.read()) for h in handles]
audit = []
paths = []
for index in range(3):
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as tmp:
tmp.write(f"file-{index}\n")
paths.append(tmp.name)
try:
print(process_all(paths, audit))
print(audit) # ['released all handles']
finally:
for path in paths:
os.unlink(path)
with ExitStack() as stack:
stack.enter_context(tempfile.TemporaryDirectory())
stack.callback(print, "teardown callback")
stack.enter_context(open(os.devnull, "w"))
print("two contexts registered on one stack")
The stack.callback registration is the escape hatch: any cleanup you can express as a function fits the same LIFO discipline, so a resource without a context-manager interface still unwinds in the right order.
Asynchronous context managers
Async code needs the same guarantee, and async with provides it through __aenter__ and __aexit__, which are awaited like any other coroutine. The practical difference is that acquisition may itself involve I/O â waiting for a connection, a lock, or a semaphore â so the manager must be written with async def, and mixing a synchronous manager into async with raises rather than silently blocking the event loop.
contextlib.asynccontextmanager mirrors the synchronous decorator for generator-based managers, and AsyncExitStack mirrors ExitStack for dynamic sets. The discipline carries over: finally blocks run on cancellation too, which matters because asyncio.CancelledError travels through await points and can interrupt a manager between acquisition and use. Cleanup that only runs on normal completion will leak under cancellation, which is exactly what happens when a request is aborted.
import asyncio
from contextlib import asynccontextmanager, AsyncExitStack
@asynccontextmanager
async def session(name, log):
await asyncio.sleep(0.01) # acquisition may wait on I/O
log.append(f"open {name}")
try:
yield {"name": name}
finally:
log.append(f"close {name}") # runs on normal exit and on cancellation
class AsyncLock:
async def __aenter__(self):
await asyncio.sleep(0.01)
self._held = True
return self
async def __aexit__(self, exc_type, exc, tb):
self._held = False
return False
async def main():
audit = []
async def note(message):
audit.append(message)
async with session("primary", audit) as conn:
async with AsyncLock():
await asyncio.sleep(0.01)
print(conn["name"])
async with AsyncExitStack() as stack:
await stack.enter_async_context(session("second", audit))
stack.push_async_callback(note, "async teardown")
print(audit)
asyncio.run(main())
A subtle trap in async managers is doing blocking work inside __aenter__. Calling requests.get or open on a large file without an executor stalls the whole event loop, so blocking calls belong behind asyncio.to_thread or in an explicitly asynchronous API.
Choosing the right implementation
Four implementations cover the space, and the choice is decided by whether you need precise control over exceptions, whether the resource set is dynamic, and whether the work is asynchronous.
| Need | Use | Notes |
|---|---|---|
| File, lock, or transaction with a class already | Class with __enter__ and __exit__ | Full control over suppression and state |
| Small resource with simple cleanup | @contextmanager | Shortest correct version |
| Variable number of resources | ExitStack | LIFO unwinding, supports callback |
| Registration or patching around a block | contextlib.closing or patch patterns | Standard library handles the discipline |
| Async acquisition or I/O | async with and @asynccontextmanager | Must not block the event loop |
| Teardown of an object you do not own | contextlib.closing | Calls .close() for you |
A rule of thumb for library code: prefer the class form when the manager holds state or might be subclassed, and the generator form when it is a one-off wrapper around an existing resource. Both are correct; the class version simply leaves room to grow.
Testing that cleanup actually happens
Managers are easy to test and rarely tested, which is how a cleanup regression reaches production. The highest-value assertions are structural rather than behavioural: that __exit__ runs when the body raises, that resources release in reverse order, that a suppression decision is the intended one, and that cleanup runs when the block is abandoned early with return. Each of these is a three-line test, and together they cover the paths that only execute during failures.
import pytest
from contextlib import ExitStack
class Recorder:
def __init__(self):
self.events = []
def __enter__(self):
self.events.append("enter")
return self
def __exit__(self, exc_type, exc, tb):
self.events.append("exit")
return False
def test_cleanup_runs_when_body_raises():
rec = Recorder()
with pytest.raises(ValueError):
with rec:
raise ValueError("boom")
assert rec.events == ["enter", "exit"]
def test_release_order_is_reverse():
order = []
with ExitStack() as stack:
stack.callback(order.append, "first")
stack.callback(order.append, "second")
assert order == ["second", "first"]
def test_early_return_still_exits():
rec = Recorder()
def body():
with rec:
return "early"
assert body() == "early"
assert rec.events == ["enter", "exit"]
Write these once for your own managers and adapt them. The cost is minutes; the alternative is discovering that a lock or a file handle outlived the block that owned it, usually during an incident.
Common Mistakes
Returning a truthy value from __exit__ without actually handling the exception
Fix: Return False or nothing at all; suppression must be deliberate and paired with real recovery
Yielding twice in a @contextmanager function
Fix: A generator-based manager yields exactly once â restructure with a helper if you need two phases
Catching broadly after the yield and not re-raising
Fix: Reraise, or translate with raise ... from err, so the caller learns the block failed
Doing blocking I/O inside async __aenter__ or __exit__
Fix: Wrap blocking calls with asyncio.to_thread or use an asynchronous API so the loop stays responsive
Assuming cleanup runs only on the happy path
Fix: Test the raising path explicitly â finally and __exit__ must both fire when the body fails
Best Practices
- Keep setup and teardown in one context manager instead of scattered try and finally blocks
- Use ExitStack whenever the resource count is determined at run time
- Put unconditional cleanup in finally and error translation in except
- Mirror the synchronous design with asynccontextmanager and AsyncExitStack in async code
- Assert release order and cleanup-on-raise in tests for every manager you write
Interview Questions
Q1: What do the three arguments to __exit__ mean and what does returning True do?
They are the exception type, value, and traceback â all None on a clean exit. Returning True tells Python to suppress a propagating exception, so the with block appears to have succeeded even though it raised.
Q2: What are the restrictions on a @contextmanager generator?
It must yield exactly once; a second yield raises RuntimeError. It may raise before the yield to fail entry, and exceptions thrown in at the yield point should be re-raised unless you are deliberately handling them.
Q3: When would you use ExitStack instead of nested with statements?
When the number or identity of resources is known only at run time â a list of files, a set of locks â or when mixing several manager types. ExitStack unwinds them in reverse order, matching what nesting would have done.
Key Takeaways
- __exit__ sees every exception and its return value decides suppression
- Generator managers yield once, with finally for cleanup and explicit re-raise for errors
- ExitStack unwinds dynamic resource sets in reverse acquisition order
- async with needs __aenter__ and __aexit__ and must never block the event loop
- Test cleanup on the raising path â that is where guarantees are usually lost