Skip to content
Transfer cleanup responsibility with ExitStack.pop_all

Transfer cleanup responsibility with ExitStack.pop_all

November 24, 2026

ExitStack.pop_all() moves registered cleanup callbacks into another stack without running them. This is useful when a setup function acquires resources successfully and hands their lifetime to its caller.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:

demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1

Save as demo_cleanup_transfer.py in that directory. Use this filename to avoid shadowing a standard-library module.

from contextlib import ExitStack

events = []
with ExitStack() as setup:
    setup.callback(events.append, "close first")
    setup.callback(events.append, "close second")
    owner = setup.pop_all()

print("After setup:", events)
try:
    print("Caller owns cleanup")
finally:
    owner.close()
print("After owner close:", events)
owner.close()
print("After second close:", events)

Run it:

python3 demo_cleanup_transfer.py

Captured output:

After setup: []
Caller owns cleanup
After owner close: ['close second', 'close first']
After second close: ['close second', 'close first']

Interpret the result

The setup stack is empty after the transfer, so leaving its with block runs nothing. Closing the returned stack runs callbacks in reverse registration order. A second close has no remaining callbacks. These callbacks only append messages; no real files are opened. For actual resources, the caller must retain and close the returned stack, preferably with a context manager. Discarding it is not a cleanup plan: garbage collection does not run its callbacks. Arrange ownership before returning so an intervening failure cannot abandon the stack.

See the version-specific Python reference for the API contract.

Clean up

In the same Bash session, remove the source file and then the empty working directory:

rm -- demo_cleanup_transfer.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dir

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on