Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

ExitStack.enter_context(): managing contexts dynamically

Use `ExitStack.enter_context()` when you decide at runtime which contexts to enter. Get each entry value back and clean up in reverse registration order.

Version: Python 3.12

Syntax

with contextlib.ExitStack() as stack:
    value = stack.enter_context(cm)
    # Use value here.
    stack.close()  # Optional: run cleanup before leaving the block.

contextlib.ExitStack.enter_context(cm) immediately calls __enter__() on the synchronous context manager cm. After a successful entry, it registers that manager’s __exit__() and returns the result of __enter__()—the value that with cm as value would assign to value. This lets you add managers in a loop or conditionally. In Python 3.12, passing an object that does not support this protocol raises TypeError.

Register managers inside with ExitStack() as stack:. On exit, cleanup runs in reverse registration order (LIFO), like nested with blocks. If a later __enter__() raises, its __exit__() is not registered, but earlier exit routines still run as the block unwinds and can handle or suppress the exception.

stack.close() runs pending cleanup immediately, starting with no exception information. Once the stack is drained, leaving with does not repeat those calls. Do not rely on garbage collection: it does not run the stack’s exit routines.

In the example, redirect_stdout() restores the previous sys.stdout without closing the StringIO buffer, so getvalue() can still read it. Redirection changes the global sys.stdout, does not capture subprocess output, and is unsuitable for library code and most threaded applications.

Examples

from contextlib import ExitStack, contextmanager, redirect_stdout
from io import StringIO


@contextmanager
def capture(label):
    try:
        with redirect_stdout(StringIO()) as buffer:
            yield buffer
    finally:
        print(f"restored after {label}")


captured = {}
with ExitStack() as stack:
    for label in ("outer", "inner"):
        captured[label] = stack.enter_context(capture(label))
        print(label)

    stack.close()
    print("still inside with")

for label, buffer in captured.items():
    print(f"{label}: {buffer.getvalue()!r}")

Result

restored after outer
still inside with
outer: 'outer\nrestored after inner\n'
inner: 'inner\n'

The loop registers two managers. Calling `stack.close()` inside `with` first restores the outer buffer, which receives `restored after inner`, and then restores the original output stream, which receives `restored after outer` and `still inside with`.

Related lessons

  • Python · Lesson 12 · Advanced · Version: 5
  • Python · Lesson 23 · Intermediate · Version: 3

Sources