PyDocs

Nav

Python Runtime Services

ExitStack

contextlib

class · Added in 3.3 (source)
Context manager for dynamic management of a stack of exit callbacks.

For example:
    with ExitStack() as stack:
        files = [stack.enter_context(open(fname)) for fname in filenames]
        # All opened files will automatically be closed at the end of
        # the with statement, even if attempts to open files later
        # in the list raise an exception.
Members of ExitStack

c

callback
Registers an arbitrary callback and arguments.
close
Immediately unwind the context stack.

e

enter_context
Enters the supplied context manager.

p

pop_all
Preserve the context stack by transferring it to a new instance.
push
Registers a callback with the standard __exit__ method signature.
1 Example
>>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
...     stack.callback(print, "Callback: from first context")
...     print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
...     stack.callback(print, "Callback: from second context")
...     print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
...     stack.callback(print, "Callback: from outer context")
...     with stack:
...         stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context
from the Python docs
See Also
No see-alsos for contextlib/ExitStack
0 Notes
No notes for ExitStack