ExitStack
- Python course
- Intermediate
- Lesson 110/116
- 5 min
Learn dynamic context management with ExitStack.
ExitStack
ExitStack dynamically manages multiple context managers. It is ideal when the number is not known in advance:
from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(print, "bitti")
print("içeride")
# bittiHere stack.callback(print, "bitti") schedules a print("bitti") call at block end. ExitStack runs all callbacks in reverse order.
This is a flexible tool for dynamic cleanup.
callback and enter_context
ExitStack offers two main methods. callback(fn, *args) schedules a function call at block end. enter_context(cm) adds a context manager to the ExitStack:
with ExitStack() as stack:
stack.callback(print, "temizlik")
f = stack.enter_context(open("dosya.txt"))Cleanup happens in reverse order of addition — last added is closed first. This ensures safe management of multiple resources.
This is standard for dynamic resource management.
Practice Schedule a callback with ExitStack
Write from contextlib import ExitStack. Inside a with ExitStack() as stack: block write stack.callback(print, "bitti") and print("içeride").
Starter code
# import ExitStack
# schedule cleanup with callbackSample solution
from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(print, "bitti")
print("içeride")Expected output
içeride bitti
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ExitStack import
from contextlib import ____
with ExitStack() as stack:
stack.callback(print, "bitti")
from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(print, "bitti")
Explanation: ExitStack comes from the contextlib module.
2 In which order does ExitStack run callbacks?
- Randomly
- In addition order
- In reverse order Correct answer
- Only the first
Explanation: ExitStack runs callbacks in reverse order (LIFO).
3 Match ExitStack concepts
| Term | Meaning |
|---|---|
ExitStack |
Dynamic manager |
callback |
Schedules cleanup |
enter_context |
Adds a cm |
reverse order |
Closing order |