Python contextlib.ExitStack
ExitStack manages context managers acquired at runtime. Leaving the with block unwinds all registered resources in reverse registration order.
A simple example
contextlib.ExitStack
- Start with A reader containing A
- Do this Read inside a managed block
- Result A, then reader closed
Syntax
stream = stack.enter_context(context_manager)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Close a variable number of streams together
A program opens a reader to process records and can finish before reaching the last one. Keep operations inside the reader's lifetime and release the open resource when the work completes.
from contextlib import ExitStack
from io import StringIO
with ExitStack() as stack:
streams = [stack.enter_context(StringIO(value)) for value in ("A", "B")]
print("".join(stream.read() for stream in streams))
print(all(stream.closed for stream in streams))
AB True
Read the contents while the stack is active. Assigning a stream to a variable outside the block keeps a reference to it but does not keep the stream open.
Python documentation for contextlib.ExitStack
Finish a rehearsal import
A music teacher reads an attendance note using a scoped reader. The operator finishes reading inside a managed resource scope. What is the reader’s state after leaving the scope?
Complete a shift handover
A supervisor reads a handover note to the end inside a cleanup block. The operator finishes reading inside a managed resource scope. What is the reader’s state after leaving the scope?