On this page
atexit
Prev: asyncio | Up: stdlib_module | Next: base64
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — atexit
Tags: #public #python3 #stdlib
Import
import atexit
Overview
Registers cleanup callbacks to run in reverse (LIFO) order during normal Python interpreter shutdown (register, unregister). Reach for atexit as a last-resort safety net for flushing buffers or deleting process-wide lock files; always prefer with context managers (contextlib) for deterministic resource cleanup.
Quick Start
import atexit
log: list[str] = []
def on_exit(tag: str) -> None:
log.append(tag)
atexit.register(on_exit, "cleanup")
atexit.unregister(on_exit)
assert log == []
Implementation Walkthrough
1. Decorator Syntax & LIFO Execution Order
Callbacks execute in last-in, first-out order (just like ExitStack), so later resources tear down before the dependencies they rely on:
import atexit
@atexit.register
def flush_metrics() -> None:
# Runs on normal interpreter exit
pass
2. Unregistering Once Explicit Cleanup Already Ran
import atexit
from pathlib import Path
def create_pidfile(path: Path) -> None:
path.write_text("12345\n", encoding="utf-8")
def cleanup() -> None:
path.unlink(missing_ok=True)
atexit.register(cleanup)
Gotchas & Boundaries
- Does NOT run on hard crashes or signals:
SIGKILL,os._exit(), fatal C segfaults, and unhandledSIGTERM(unless caught via signal) bypassatexithandlers completely. - Avoid raising exceptions inside
atexitcallbacks: Unhandled exceptions print a traceback to stderr during shutdown and do not stop remaining handlers. - Don't rely on
atexitfor closing files or DB transactions: Usewithblocks so cleanup happens immediately, not at process exit.
Common Functions
- atexit.register() —
register(func, /, *args, **kwargs)— Register a function to be executed upon normal program termination func - function to be called at exit args - optional arguments to pass to func - atexit.unregister() —
unregister(func, /)— Unregister an exit function which was previously registered using atexit.register func - function to be unregistered
Linked from
Related notes
- tuts/python3/stdlib_module/asyncio Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/atexit/register Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/atexit/unregister Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/base64 Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/readline links to this page; shared tags: #stdlib