Sub topic 10
ExitStack for a variable number of managers
This chapter assumes you know how with works, how __enter__ and __exit__ behave, and how to nest or combine several managers in one with statement. It also assumes you can read basic try/except/finally code.
The problem: the count is not known in advance
A with statement lists its managers in the source code. That works when you know how many resources you need. It fails when the number comes from data, such as a list of file paths of unknown length.
You cannot write a with line with "N" managers. A common workaround is to open the files in a loop and close them yourself. That brings back the problem with was meant to solve: if the third open() fails, the first two files stay open.
contextlib.ExitStack solves this. It is a context manager that holds other context managers. You add them one at a time, and when the block ends, it closes all of them.
Entering managers with enter_context
Here is the example from the plan. It joins any number of files into one.
from contextlib import ExitStack
def concatenate(paths, out_path):
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
with open(out_path, "w") as out:
for f in files:
out.write(f.read())stack.enter_context(cm) does two things. It calls cm.__enter__() and returns the result, so you can use it like an as value. It also records cm so that its __exit__ runs when the stack closes.
If the fourth open() raises FileNotFoundError, the stack is already inside its with block. It closes the three files that were opened, then lets the error continue upward.
Order of cleanup and exception handling
ExitStack closes its managers in last-in, first-out order. This is the same order that nested with statements use.
from contextlib import ExitStack, contextmanager
@contextmanager
def tracked(name):
print("open", name)
try:
yield name
finally:
print("close", name)
with ExitStack() as stack:
for name in ["a", "b", "c"]:
stack.enter_context(tracked(name))
print("working")The output is open a, open b, open c, working, then close c, close b, close a.
If an exception is raised in the block, each manager's __exit__ receives it in turn, just as with nested with statements. A manager that returns a true value suppresses it. The managers below it in the stack then see no exception.
Adding plain cleanup with callback
Not every cleanup action is a context manager. stack.callback(func, *args, **kwargs) registers an ordinary function to call on exit. Callbacks run in the same reverse order as everything else.
from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(print, "cleanup one")
stack.callback(print, "cleanup two")
print("body")This prints body, cleanup two, cleanup one. A callback cannot see or suppress the exception. Use stack.push(exit_func) if you need a function with the full __exit__ signature.
Conditional and optional resources
ExitStack is also useful when a resource is needed only sometimes. You enter it inside an if, and the stack still cleans it up at the end.
from contextlib import ExitStack
def process(path, log_path=None):
with ExitStack() as stack:
src = stack.enter_context(open(path))
log = stack.enter_context(open(log_path, "a")) if log_path else None
for line in src:
if log:
log.write(line)The simpler contextlib.nullcontext is often enough for a single optional resource. Use ExitStack when several optional resources interact.
Keeping the resources open longer: pop_all
Sometimes you want to acquire several resources safely, and then hand them to someone else. pop_all() moves everything to a new ExitStack and leaves the original empty. If setup fails partway, the original stack still cleans up. If setup succeeds, you call pop_all() and return the new stack.
from contextlib import ExitStack
def open_all(paths):
with ExitStack() as stack:
files = [stack.enter_context(open(p)) for p in paths]
return files, stack.pop_all()
files, closer = open_all(["a.txt", "b.txt"])
try:
print([f.name for f in files])
finally:
closer.close()Call close() on the returned stack, or use it in its own with. Forgetting to do so leaks the files.
Summary of the main methods
| Method | What it does |
|---|---|
| `enter_context(cm)` | Enters `cm` and schedules its `__exit__`. Returns the `__enter__` result. |
| `callback(f, *a, **k)` | Schedules a plain function call on exit. |
| `push(exit_func)` | Schedules a function with the `__exit__` signature. |
| `pop_all()` | Moves all scheduled actions to a new stack. |
| `close()` | Runs the scheduled actions now, as if leaving the block. |
Exercise
You write files = [open(p) for p in paths] and then with ExitStack() as stack: and add each file with stack.enter_context(f). If the third open() raises an error, what happens to the first two files, and how do you fix the code?
Show answer
The first two files are never closed. The error occurs in the list comprehension, before the ExitStack block begins, so no cleanup is registered. The fix is to create the stack first and call stack.enter_context(open(p)) for each path inside the with ExitStack() block. Then each file is registered as soon as it is opened, and an error on the third file closes the first two.