On this page
  1. atexit
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Decorator Syntax & LIFO Execution Order
  7. 2. Unregistering Once Explicit Cleanup Already Ran
  8. Gotchas & Boundaries
  9. Common Functions

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

Common Functions

Linked from

Related notes