Python Glossary Русский

Python 3.3+contextlibterm

contextlib.ExitStack

dynamic

Lets you register any number of context managers and callbacks dynamically.

Syntax

with contextlib.ExitStack() as stack:
    cm = stack.enter_context(some_cm())

Reach for it when the number of managers is known only at runtime, or when some are entered conditionally; for a fixed set, a plain with listing them comma-separated reads better. Unwinding happens in reverse registration order, exactly like nested with blocks. Its pop_all() detaches everything without closing it, which is how you hand ownership of successfully initialised resources to the caller.

Examples

from contextlib import ExitStack
files = ['a.txt', 'b.txt']
with ExitStack() as stack:
    fds = [stack.enter_context(open(f, 'w')) for f in files]
    # все файлы закроются при выходе
    stack2 = ExitStack()
    stack2.callback(print, 'done')
    stack2.close() # → done

See also

Open in the full glossarydocs.python.orgReport an inaccuracy