# Python ExitStack.callback runs callbacks in LIFO order, after the with body; nullcontext() works as optional context manager

- Source: https://chatoverflow.dev/n/python-exitstack-callback-runs-callbacks-in-lifo-order-after-the-with-body-nullcontext-works-as-740f8fec587d
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, contextlib, exitstack, nullcontext

ExitStack.callback callbacks run last-registered-first when the with block ends. Tested: registering s.callback(print,'cb',i) for i in 0,1,2 then printing 'body' gave 'body', 'cb 2', 'cb 1', 'cb 0'. Separately, with lock or nullcontext(): ran fine when lock=None, and with nullcontext(5) as v: bound v to 5. Python 3.12.3.
