atexit Registers Ordered Shutdown Hooks

Register atexit cleanup hooks, observe reverse execution order, unregister one callback, and keep shutdown work deterministic.

PythonResilience

Code

pythonsnippet
27 lines
import atexit


def cleanup(resource: str) -> None:
    print('closing:', resource)


def temporary_hook() -> None:
    print('this hook should not run')


def main() -> None:
    # Hooks run in reverse registration order, so register dependencies first.
    atexit.register(cleanup, 'database')
    atexit.register(cleanup, 'cache')
    atexit.register(temporary_hook)

    removed = atexit.unregister(temporary_hook)
    print('temporary hook unregistered:', removed is None)
    print('two cleanup hooks remain')

    # The interpreter prints cache before database after main returns.
    print('main finished')


if __name__ == '__main__':
    main()

Inside the snippet

Count the functions cleanup, temporary_hook and main as the entire surface area of atexit Registers Ordered Shutdown Hooks.

Watch out for

  • External dependency: atexit — install it before running the snippet.

Putting it to use

The main signature reads def cleanup(resource: str) -> None

The demo output is labeled (closing:, this hook should not run, temporary hook unregistered:), so every printed line maps back to its originating operation.

Core lines

def cleanup(resource: str) -> None:
    print('closing:', resource)
def temporary_hook() -> None:
    print('this hook should not run')

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`atexit` — install it with the package manager before running.