Sub topic 10
ExitStack for a variable number of managers
This chapter assumes you can write a basic with statement, know the __enter__ and __exit__ protocol, and understand how exceptions travel through __exit__. It also assumes you know that with blocks unwind in reverse order. Everything else is introduced as it appears.
The problem a fixed with statement cannot solve
A with statement lists its managers in the source code. That works when you know at write time how many resources you need:
with open("a.txt") as a, open("b.txt") as b:
print(a.read() + b.read())It breaks down when the number depends on data. Suppose a function receives a list of paths of unknown length and must keep every file open at once. You cannot write a with line with a variable number of open() calls. Nesting with blocks in a loop does not help, because each block closes its file when the loop body ends.
Other situations have the same shape:
- A manager is needed only if an option is set, such as writing to a file instead of standard output.
- Several resources are acquired in
__init__, and all of them must be released if any one acquisition fails. - Cleanup code is a plain function with no
__exit__method.
contextlib.ExitStack handles all of these. It is a context manager that holds other context managers and cleanup functions, and it releases them together when its own block ends.
The basic pattern
You create an ExitStack in a with statement. Inside the block you call stack.enter_context(manager) for each manager you want to add. This calls the manager's __enter__, returns its result (the same value an as clause would give you), and registers the manager's __exit__ for later.
from contextlib import ExitStack
from pathlib import Path
import tempfile
def concatenate(paths, out_path):
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
out = stack.enter_context(open(out_path, "w"))
for f in files:
out.write(f.read())
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
sources = []
for i in range(4):
p = tmp / f"part{i}.txt"
p.write_text(f"part {i}\n")
sources.append(p)
concatenate(sources, tmp / "all.txt")
print((tmp / "all.txt").read_text())The output is the four lines part 0 through part 3. The function works the same for 2 paths or 2,000. When the with ExitStack() block ends, every file closes.
The stack is safe against partial failure. If the third open() raises FileNotFoundError, the first two files are already registered. The stack's __exit__ runs as the exception propagates, closes them, and lets the error continue.
How the stack unwinds
ExitStack keeps an internal list of exit callbacks. Each call to enter_context or callback pushes one entry. When the block ends, the stack pops entries one at a time, newest first, and calls each with the current exception information. This is the same last-in, first-out order you get from nested with statements.
Because the stack records only what has been registered so far, it never tries to release something that was not acquired. That is the main reason to prefer it over hand-written try/finally chains for several resources.
The methods you will use
| Method | What it does |
|---|---|
| `enter_context(cm)` | Enters `cm`, registers its `__exit__`, and returns the value `__enter__` returned. |
| `callback(func, *args, **kwargs)` | Registers a plain function to call at exit. Its return value is ignored and it cannot suppress exceptions. |
| `push(exit_or_cm)` | Registers an object with an `__exit__` method, or a function with the `__exit__` signature, without calling `__enter__`. |
| `pop_all()` | Moves all registered entries into a new `ExitStack` and leaves the original empty. |
| `close()` | Unwinds the stack immediately, as if the `with` block had ended without an exception. |
Registering plain cleanup functions
callback is useful when the thing to undo is not a context manager. The callbacks run in reverse order of registration:
from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(print, "cleanup 1")
stack.callback(print, "cleanup 2")
print("body")This prints body, then cleanup 2, then cleanup 1. Arguments are captured at registration time, so stack.callback(print, x) uses the value x had when you called callback, not when the cleanup runs.
callback also returns the function you passed, so it can be used as a decorator:
from contextlib import ExitStack
with ExitStack() as stack:
@stack.callback
def say_goodbye():
print("goodbye")
print("working")Conditional managers
A fixed with cannot say "enter this manager only if a flag is set." With ExitStack you use an ordinary if:
import sys
from contextlib import ExitStack
def write_report(lines, path=None):
with ExitStack() as stack:
if path is None:
out = sys.stdout
else:
out = stack.enter_context(open(path, "w"))
for line in lines:
out.write(line + "\n")
write_report(["alpha", "beta"])
write_report(["alpha", "beta"], path="report.txt")When path is None, the stack stays empty and nothing is closed. This matters here because closing sys.stdout would break later printing. For a simpler single case, contextlib.nullcontext(sys.stdout) also works. ExitStack pays off when several optional resources are involved.
Exceptions inside the stack
ExitStack follows the normal __exit__ rules, applied to each entry in turn.
- An exception raised in the body is passed to the newest callback first. If that callback's
__exit__returns a true value, the exception is suppressed for all older entries, which then see no exception. - If a cleanup itself raises, the new exception replaces the old one for the remaining entries, and Python chains the original through
__context__. The remaining cleanups still run. - If any entry suppressed the exception,
ExitStack.__exit__returnsTrueand execution continues after thewithblock.
This example shows that a failing cleanup does not stop the others:
from contextlib import ExitStack
try:
with ExitStack() as stack:
stack.callback(print, "second cleanup runs")
stack.callback(lambda: 1 / 0)
print("body")
except ZeroDivisionError as e:
print("caught:", e)The output is body, then second cleanup runs, then caught: division by zero. The lambda is registered last, so it runs first and raises. The print cleanup still runs, and the ZeroDivisionError then propagates.
To suppress exceptions you can push a function with the __exit__ signature:
from contextlib import ExitStack
def ignore_value_error(exc_type, exc, tb):
return exc_type is not None and issubclass(exc_type, ValueError)
with ExitStack() as stack:
stack.push(ignore_value_error)
int("not a number")
print("continued")Transferring ownership with pop_all
The most valuable ExitStack feature for real code is pop_all(). It solves this problem: a constructor acquires several resources, and any acquisition might fail. On failure you want everything released. On success you want everything kept open for the caller to release later.
from contextlib import ExitStack
from pathlib import Path
import tempfile
class MultiFile:
def __init__(self, paths):
with ExitStack() as stack:
self.files = [stack.enter_context(open(p)) for p in paths]
# Reached only if every open() succeeded.
self._stack = stack.pop_all()
def close(self):
self._stack.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False
with tempfile.TemporaryDirectory() as tmp:
paths = []
for name in ("one", "two"):
p = Path(tmp) / f"{name}.txt"
p.write_text(name)
paths.append(p)
with MultiFile(paths) as mf:
print([f.read() for f in mf.files])
print([f.closed for f in mf.files])This prints ['one', 'two'] and then [True, True].
If any open() in the constructor fails, the exception leaves the inner with ExitStack() block while the stack still holds the registrations. The files already opened are closed. If all opens succeed, pop_all() moves the registrations into self._stack and leaves the original stack empty. The inner with then exits without closing anything. Ownership has moved to the new stack, and close() releases it later.
Using ExitStack without a with block
You can create a stack, register things, and call close() yourself, for example when resource lifetimes follow an object's lifetime rather than a code block. In that case wrap the risky part in try/finally, or use pop_all() as above, so that a failure during setup still releases what was acquired. If you call close() manually and forget to, nothing releases the resources.
Common mistakes
- Expecting
callbackto see exceptions. A function registered withcallbackreceives only the arguments you gave it, and its return value is ignored. Usepushwith an__exit__-style function if you need to inspect or suppress an exception. - Capturing late-binding variables.
stack.callback(lambda: print(x))readsxwhen the cleanup runs. Pass arguments tocallbackinstead:stack.callback(print, x). - Entering the stack's resources after the
withhas ended. Once the block exits, the stack is empty. Reusing it works technically, but anything registered after that point is not released until you callclose()or enter a new block. - Reaching for
ExitStackwhen a plainwith a, b:is enough. For a known, small number of managers, the multi-managerwithstatement is shorter and easier to read.
Exercises
Exercise
What does this code print, and in what order? from contextlib import ExitStack with ExitStack() as stack: for name in ("a", "b", "c"): stack.callback(print, "closing", name) print("body done")
Show answer
It prints "body done", then "closing c", "closing b", "closing a". The body runs first. At the end of the block the stack calls its callbacks newest first, so the cleanup order is the reverse of the registration order.
Exercise
Write a function open_all(paths) that opens every file in paths for reading and returns a pair (files, stack), where stack is an ExitStack the caller will close later. If any open() fails, every file opened so far must be closed and the error must propagate. Which method makes this possible?
Show answer
Use popall(): from contextlib import ExitStack def openall(paths): with ExitStack() as stack: files = [stack.entercontext(open(p)) for p in paths] return files, stack.popall() If an open() fails, the inner stack closes the files already opened and the exception propagates. If all succeed, pop_all() moves the registrations to a new stack, so the with block exits without closing anything. The caller later calls stack.close() on the returned stack.