with statements are one of Python’s best features — until the number of resources you need to manage isn’t known until runtime. Need to open ten files? Fifty sockets? A transaction plus a lock plus a temp directory that may or may not be created? Nesting with blocks stops working the moment the count is dynamic.
contextlib.ExitStack is the standard-library answer: it lets you register an arbitrary number of context managers and unwinds them all automatically when the block ends. Here’s what it does well, and three traps that bite people who treat it like a plain with.

The problem: with needs a fixed number of managers
You cannot write a with block for a list of files whose length you only learn at runtime:
# Works for two files. Fails for N files.
with open("a.log") as a, open("b.log") as b:
...
A loop with open() and a hand-written try/finally gets ugly fast, and it is easy to leak a handle when the third open() raises after the first two succeeded.
The fix: enter_context()
ExitStack is itself a context manager. Inside it, register any number of other context managers with enter_context(), which calls __enter__() and returns its value — exactly like with would:
from contextlib import ExitStack
def merge_logs(paths, out_path):
with ExitStack() as stack:
sources = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
dest = stack.enter_context(open(out_path, "w", encoding="utf-8"))
for src in sources:
dest.writelines(src)
# every file is closed here — even if open() or writelines() raised
If open() fails halfway through the list comprehension, the files opened so far are still closed. That safety is the whole reason to reach for this tool.
Gotcha 1: cleanup runs last-in, first-out
ExitStack unwinds callbacks in reverse registration order, mirroring nested with statements. This matters when order carries meaning — for example, releasing a lock before committing a transaction:
with ExitStack() as stack:
tx = stack.enter_context(transaction()) # entered 1st → exited 2nd
lock = stack.enter_context(my_lock()) # entered 2nd → exited 1st
If your teardown has a required order, register in the opposite order, or make the dependency explicit instead of relying on the implicit LIFO rule.
Gotcha 2: callback() does not suppress exceptions
stack.callback(fn) is handy for cleanup that isn’t a context manager (closing a raw resource, logging a completion message). But plain callbacks are invoked with no exception arguments, and their return value is ignored — so returning True will not swallow the error:
with ExitStack() as stack:
stack.callback(lambda: True) # does NOT suppress; return value ignored
raise ValueError("still propagates")
When you need suppression, use a real context manager via enter_context() and implement __exit__ returning True. Reserve callback() for side-effect cleanup that must always run.
Gotcha 3: a failing cleanup can mask the original exception
If a cleanup callback itself raises, that new exception replaces the original one — the original is preserved in __context__, but the traceback you see points at the cleanup code:
try:
with ExitStack() as stack:
stack.callback(lambda: 1 / 0)
raise ValueError("the real bug")
except Exception as e:
print(type(e).__name__) # ZeroDivisionError ← masks the bug
print(type(e.__context__)) # ValueError ← the real cause
Keep cleanup callbacks small and non-throwing. If a cleanup step can legitimately fail, catch inside it and log, so it cannot hide the exception that brought you there. (This is not unique to ExitStack — nested with blocks behave the same way — but stacking many callbacks makes it more likely.)
Bonus: pop_all() to hand off ownership
Sometimes you want to build up a set of resources and transfer responsibility elsewhere instead of closing at the end of the block. pop_all() moves every registered callback into a fresh stack, leaving the original empty:
with ExitStack() as stack:
conn = stack.enter_context(connect())
held = stack.pop_all() # original stack won't close conn on exit
# conn is still open; `held` now owns closing it
return held, conn
This is the clean way to return resources from a factory function without leaking them.
When to reach for it
- Opening a runtime-determined number of files, sockets, or cursors.
- Combining a transaction + lock + temporary directory where any setup step can fail.
- Building a “register a cleanup” API in a library or framework.
- Transferring resource ownership across scopes with
pop_all().
ExitStack does not replace with — for a fixed, known set of resources, plain nested with is clearer. It is the tool for the moment when the count or the set is decided at runtime, and you still want with-level safety.