Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

ExitStack.close(): explicit LIFO cleanup

Register context managers at runtime, then call `stack.close()` to release their resources in reverse registration order before the enclosing `with` block ends.

Version: Python 3.12

Syntax

from contextlib import ExitStack

with ExitStack() as stack:
    for cm in managers:
        value = stack.enter_context(cm)
        # Use value while its context is active.
    stack.close()

When the number of context managers depends on input, call stack.enter_context(cm) inside with ExitStack() as stack:. It calls cm.__enter__(), returns its result, and registers cm.__exit__() after entry succeeds. If entering a later context fails, the with block still ensures that the exit callbacks for previously registered contexts are called.

contextlib.ExitStack.close is a synchronous method you call without arguments as stack.close(). It immediately removes and runs the registered callbacks in reverse registration order (LIFO). It does not leave the with block: if the call returns normally, execution continues. Leaving the block does not run the callbacks that were already removed. Do not use resources that cleanup has released.

An explicit close() starts cleanup as if no exception had occurred. By contrast, if an exception leaves the with body, automatic exit passes its details to the exit callbacks still on the stack. If a callback raises or suppresses an exception during cleanup, later exit callbacks see the updated exception state. An unsuppressed cleanup exception can propagate from close().

Call close() when cleanup must happen before the block ends. Otherwise, let with handle cleanup automatically. Garbage collection does not run the registered callbacks.

Examples

from contextlib import ExitStack, contextmanager


@contextmanager
def traced(name):
    print(f"enter {name}")
    try:
        yield name
    finally:
        print(f"exit {name}")


names = ["A", "B", "C"]
with ExitStack() as stack:
    active = [stack.enter_context(traced(name)) for name in names]
    print("use:", ", ".join(active))
    stack.close()
    print("still inside")
print("outside")

Result

enter A
enter B
enter C
use: A, B, C
exit C
exit B
exit A
still inside
outside

`names` determines which contexts are registered inside `with`. In the expected output, the `exit` lines appear in C, B, A order before `still inside`. Leaving the block does not print them again.

Related lessons

  • Python · Lesson 12 · Advanced · Version: 5

Sources