Library contents

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

  1. Start with A reader containing A
  2. Do this Read inside a managed block
  3. Result A, then reader closed
The resource manager closes the reader when the block ends.

Syntax

Python 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.

First output lineAB
lesson.py
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))
Output
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

Advertisements

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?

GivenRead “Attendance” → leave scope
Worked resultClosed

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?

GivenRead “Counted” → leave scope
Worked resultClosed