Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

contextlib.ExitStack

Accumulates context managers and cleanup callbacks chosen at runtime and unwinds them on scope exit.

Version: Python 3.14; repository image, production runtime not attested

Syntax

with contextlib.ExitStack() as stack:

Accumulates context managers and cleanup callbacks chosen at runtime and unwinds them on scope exit.

Callbacks execute in reverse registration order, which allows dependent resources to be released before their prerequisites.

Register a variable number of resources at runtime. enter_context enters a manager and records its exit; callback records a function without exception information. Stack exit or close unwinds in reverse registration order. pop_all transfers the actions without running them. The sample prints work first and releases second before first. callback cannot suppress errors. In contrast, an exit function registered through push receives the exception triple and can suppress by returning truthy.

from contextlib import ExitStack
seen = []
with ExitStack() as original:
    original.callback(seen.append, 1)
    original.callback(seen.append, 2)
    owned = original.pop_all()
assert not seen
owned.close()
assert seen == [2, 1]
with ExitStack() as s:
    s.push(lambda typ, exc, tb: typ is KeyError)
    raise KeyError("handled")

contextlib.ExitStack.enter_context · contextlib.ExitStack.close

enter_context(cm) calls __enter__, registers exit after successful entry and returns the entry value. close() unwinds in reverse registration order as a normal exit with no exception. Closing an already empty stack invokes nothing.

from contextlib import ExitStack
events=[]
class Lease:
    def __init__(self, name): self.name=name
    def __enter__(self): return self.name.upper()
    def __exit__(self,*exc): events.append((self.name,exc[0]))
stack=ExitStack()
assert stack.enter_context(Lease('a'))=='A'
assert stack.enter_context(Lease('b'))=='B'
stack.close()
stack.close()
assert events==[('b',None),('a',None)]

Examples

import contextlib
with contextlib.ExitStack() as stack:
    stack.callback(print, "first")
    stack.callback(print, "second")
    print("work")

Result

work
second
first

Register a variable number of resources at runtime. enter_context enters a manager and records its exit; callback records a function without exception information. Stack exit or close unwinds in reverse registration order. pop_all transfers the actions without running them. The sample prints work first and releases second before first. callback cannot suppress errors. In contrast, an exit function registered through push receives the exception triple and can suppress by returning truthy.

Sources