Manage Variable Resources with ExitStack
Core idea
ExitStack registers exit actions dynamically and unwinds them in reverse registration order. enter_context enters a context manager and registers its exit after successful entry. callback registers ordinary cleanup functions that cannot suppress exceptions by returning a value.
from contextlib import ExitStackwith ExitStack() as stack: stack.callback(print, "first") stack.callback(print, "second") print("work")The most recently registered callback runs first.
Close resources after failed acquisition
from contextlib import ExitStackfrom io import BytesIOclass Unavailable: def __enter__(self): raise RuntimeError("unavailable") def __exit__(self,*args): return Falsetry: with ExitStack() as stack: stream = stack.enter_context(BytesIO(b"A")) stack.enter_context(Unavailable())except RuntimeError: print(stream.closed)The successfully entered stream closes even though a later entry fails. The failed entry itself must handle its own partial acquisitions.
Common mistake
Creating an ExitStack alone does not ensure cleanup. Use with or explicitly close it. Do not rely on garbage collection to run registered callbacks.
Practice
Use enter_context in a loop to open three BytesIO objects, collect their first bytes, then verify every stream is closed after exit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ExitStack ordering
Check your understanding of exitstack.
What is printed?
from contextlib import ExitStackwith ExitStack() as s: s.callback(print,"A") s.callback(print,"B")What is printed?
from contextlib import ExitStackfrom io import BytesIOwith ExitStack() as s: a=s.enter_context(BytesIO()) b=s.enter_context(BytesIO())print(a.closed,b.closed)What can callback return to suppress a body exception?
Why use ExitStack instead of fixed nested with blocks?