Back to results for “File I/O & Context Managers”
Python › File I/O & Context Managers

How do you implement contextlib.ExitStack to dynamically manage a VARIABLE number of context managers determined at runtime?

Advanced

Answer

ExitStack lets you enter() any number of context managers PROGRAMMATICALLY (in a loop, or conditionally), and guarantees ALL of them are properly exited (in reverse order) when the ExitStack itself exits — essential when the exact number of resources to manage isn't known until runtime, unlike a fixed 'with a, b, c:' statement.
from contextlib import ExitStack

filenames = ["a.txt", "b.txt", "c.txt"]
with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    for f in files:
        process(f)
# ALL files are properly closed here, however many there were
Real-world example Opening and safely managing a dynamic, runtime-determined number of files or database connections in a single batch operation.

Common follow-ups: How does ExitStack's callback() method let you register arbitrary cleanup functions, not just full context managers?