Claude Code for atexit: Python Interpreter Shutdown Handlers — Claude Skills 360 Blog
Blog / AI / Claude Code for atexit: Python Interpreter Shutdown Handlers
AI

Claude Code for atexit: Python Interpreter Shutdown Handlers

Published: November 29, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s atexit module registers functions to call automatically when the interpreter exits normally. import atexit. Register: atexit.register(fn, *args, **kwargs) — stores (fn, args, kwargs); returns fn so it can be used as a decorator. Unregister: atexit.unregister(fn) — removes all registrations of fn (silent if not registered). Execution order: LIFO (last in, first out) — the most recently registered handler runs first, mirroring the order resources were acquired. Triggers: handlers run on normal interpreter exit (sys.exit(), end of __main__), and on exceptions that propagate to the top level; they do NOT run on os._exit(), os.abort(), SIGKILL, or when the process is killed by an uncaught signal that terminates without Python cleanup. Exception handling: if a handler raises, the traceback is printed to sys.stderr and the remaining handlers continue running. Decorator usage: @atexit.register works because register returns its first argument. Clear all: atexit._clear() — private but useful in test teardown. Manual run: atexit._run_exitfuncs() — calls all handlers immediately; each is removed after running. Claude Code generates cleanup registrars, resource finalizers, log flushers, lock releasers, and temporary file removers.

CLAUDE.md for atexit

## atexit Stack
- Stdlib: import atexit
- Register: atexit.register(fn, arg1, kwarg=val)  # returns fn
- Decorator: @atexit.register  # zero-arg function
- Unregister: atexit.unregister(fn)               # all copies removed
- Order: LIFO — last registered runs first
- Note: does NOT fire on os._exit() or SIGKILL
-       exceptions in handlers are printed, remaining handlers still run

atexit Shutdown Handler Pipeline

# app/atexitutil.py — cleanup registry, temp files, log flush, resource guard
from __future__ import annotations

import atexit
import logging
import os
import shutil
import sys
import tempfile
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path


# ─────────────────────────────────────────────────────────────────────────────
# 1. Named cleanup registry
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class CleanupEntry:
    name: str
    fn:   "callable"
    registered_at: float = field(default_factory=time.time)
    ran:  bool = False
    error: str | None = None


class CleanupRegistry:
    """
    Named cleanup registry backed by atexit.
    Tracks which handlers ran, which failed, and time of registration.

    Example:
        registry = CleanupRegistry()
        registry.register("close-db", db.close)
        registry.register("flush-cache", lambda: cache.flush())
        # handlers run automatically at exit in LIFO order
    """

    def __init__(self) -> None:
        self._entries: dict[str, CleanupEntry] = {}
        atexit.register(self._run_all)

    def register(self, name: str, fn: "callable", *args: object, **kwargs: object) -> None:
        """
        Register a named cleanup function.
        If name already exists, the old registration is replaced.

        Example:
            registry.register("close-db", conn.close)
            registry.register("flush-log", flush, level="INFO")
        """
        def _wrapped() -> None:
            fn(*args, **kwargs)

        self._entries[name] = CleanupEntry(name=name, fn=_wrapped)

    def unregister(self, name: str) -> bool:
        """Remove a named cleanup. Returns True if it existed."""
        return self._entries.pop(name, None) is not None

    def _run_all(self) -> None:
        # LIFO: reverse insertion order
        for name in list(reversed(list(self._entries))):
            entry = self._entries[name]
            try:
                entry.fn()
                entry.ran = True
            except Exception as exc:
                entry.ran = True
                entry.error = str(exc)
                print(f"[atexit] cleanup '{name}' failed: {exc}", file=sys.stderr)

    def report(self) -> list[dict]:
        return [
            {
                "name": e.name,
                "ran": e.ran,
                "error": e.error,
                "registered_at": e.registered_at,
            }
            for e in self._entries.values()
        ]


# ─────────────────────────────────────────────────────────────────────────────
# 2. Temporary path manager
# ─────────────────────────────────────────────────────────────────────────────

class TempManager:
    """
    Create temporary files and directories that are automatically removed at exit.

    Example:
        tm = TempManager()
        path = tm.mkdtemp(prefix="work_")
        # ... use path ...
        # removed at interpreter exit
    """

    def __init__(self) -> None:
        self._paths: list[Path] = []
        atexit.register(self._cleanup)

    def mkdtemp(self, **kwargs: object) -> Path:
        """Create a temporary directory and track it for deletion."""
        p = Path(tempfile.mkdtemp(**kwargs))
        self._paths.append(p)
        return p

    def mkstemp(self, **kwargs: object) -> tuple[int, Path]:
        """Create a temporary file and track it for deletion. Returns (fd, path)."""
        fd, name = tempfile.mkstemp(**kwargs)
        p = Path(name)
        self._paths.append(p)
        return fd, p

    def track(self, path: "str | Path") -> Path:
        """Track an existing path for deletion at exit."""
        p = Path(path)
        self._paths.append(p)
        return p

    def _cleanup(self) -> None:
        for p in reversed(self._paths):
            try:
                if p.is_dir():
                    shutil.rmtree(p, ignore_errors=True)
                elif p.exists():
                    p.unlink(missing_ok=True)
            except Exception:
                pass


# ─────────────────────────────────────────────────────────────────────────────
# 3. Logging flush + close on exit
# ─────────────────────────────────────────────────────────────────────────────

def register_logging_shutdown() -> None:
    """
    Register logging.shutdown() as an atexit handler.
    Ensures all log handlers flush and close cleanly before the interpreter exits.
    Safe to call multiple times (atexit deduplicates on the same function object).

    Example:
        register_logging_shutdown()
        logging.basicConfig(filename="app.log", level=logging.DEBUG)
    """
    atexit.register(logging.shutdown)


def register_file_logger(
    path: "str | Path",
    name: str = "app",
    level: int = logging.DEBUG,
) -> logging.Logger:
    """
    Create a file logger and register its handler for flush+close at exit.

    Example:
        logger = register_file_logger("/tmp/app.log")
        logger.info("started")
        # file handler flushed + closed at exit automatically
    """
    logger = logging.getLogger(name)
    handler = logging.FileHandler(str(path))
    handler.setLevel(level)
    logger.addHandler(handler)
    logger.setLevel(level)

    def _close_handler() -> None:
        handler.flush()
        handler.close()

    atexit.register(_close_handler)
    return logger


# ─────────────────────────────────────────────────────────────────────────────
# 4. Resource guard (generic acquire / release)
# ─────────────────────────────────────────────────────────────────────────────

class ResourceGuard:
    """
    Acquire a lockable resource and register its release with atexit.
    Useful for process-level locks (e.g., pid files, advisory file locks).

    Example:
        guard = ResourceGuard("my-lock", acquire=lock.acquire, release=lock.release)
        guard.acquire()
        # released at exit even if the program crashes mid-run
    """

    def __init__(
        self,
        name: str,
        acquire: "callable",
        release: "callable",
    ) -> None:
        self.name = name
        self._acquire = acquire
        self._release = release
        self._held = False

    def acquire(self) -> bool:
        """Acquire the resource and register release for atexit."""
        result = self._acquire()
        self._held = True
        atexit.register(self._release_once)
        return result

    def release(self) -> None:
        """Release immediately and unregister the atexit handler."""
        self._release_once()
        atexit.unregister(self._release_once)

    def _release_once(self) -> None:
        if self._held:
            self._held = False
            try:
                self._release()
            except Exception as exc:
                print(f"[atexit] ResourceGuard '{self.name}' release failed: {exc}",
                      file=sys.stderr)


# ─────────────────────────────────────────────────────────────────────────────
# 5. PID file helper
# ─────────────────────────────────────────────────────────────────────────────

def write_pidfile(path: "str | Path") -> Path:
    """
    Write the current PID to path and register removal at exit.
    Raises FileExistsError if the pid file already exists.

    Example:
        pidfile = write_pidfile("/var/run/myapp.pid")
    """
    p = Path(path)
    if p.exists():
        existing_pid = p.read_text().strip()
        raise FileExistsError(
            f"PID file {p} already exists (pid {existing_pid}); "
            "another instance may be running"
        )
    p.write_text(str(os.getpid()))

    def _remove() -> None:
        try:
            p.unlink(missing_ok=True)
        except Exception:
            pass

    atexit.register(_remove)
    return p


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== atexit demo ===")

    # ── @atexit.register decorator ────────────────────────────────────────────
    print("\n--- @atexit.register decorator ---")
    order: list[str] = []

    @atexit.register
    def _last_handler() -> None:
        order.append("last_handler")

    atexit.register(lambda: order.append("first_handler"))
    # LIFO: first_handler runs before last_handler
    # (shown via manual _run_exitfuncs in demo only)
    import atexit as _ax
    _ax._run_exitfuncs()
    print(f"  LIFO order: {order}")

    # ── CleanupRegistry ───────────────────────────────────────────────────────
    print("\n--- CleanupRegistry ---")
    registry = CleanupRegistry()
    log_items: list[str] = []
    registry.register("step-1", lambda: log_items.append("step-1 cleanup"))
    registry.register("step-2", lambda: log_items.append("step-2 cleanup"))
    registry.register("step-3", lambda: log_items.append("step-3 cleanup"))
    registry._run_all()   # simulate exit
    print(f"  cleanup order (LIFO): {log_items}")
    for r in registry.report():
        print(f"  {r['name']}: ran={r['ran']} error={r['error']}")

    # ── TempManager ───────────────────────────────────────────────────────────
    print("\n--- TempManager ---")
    tm = TempManager()
    tmpdir = tm.mkdtemp(prefix="atexit_demo_")
    (tmpdir / "test.txt").write_text("hello")
    print(f"  tmpdir={tmpdir.name}  exists={tmpdir.exists()}")
    tm._cleanup()   # simulate exit
    print(f"  after cleanup: exists={tmpdir.exists()}")

    # ── write_pidfile ─────────────────────────────────────────────────────────
    print("\n--- write_pidfile ---")
    with tempfile.TemporaryDirectory() as td:
        pidpath = write_pidfile(Path(td) / "demo.pid")
        print(f"  pid written: {pidpath.read_text()}  (current: {os.getpid()})")
        atexit._run_exitfuncs()
        print(f"  pid file removed: {not pidpath.exists()}")

    # ── ResourceGuard ─────────────────────────────────────────────────────────
    print("\n--- ResourceGuard ---")
    lock = threading.Lock()
    guard = ResourceGuard("demo-lock", lock.acquire, lock.release)
    guard.acquire()
    print(f"  lock held: {not lock.acquire(blocking=False)}")
    guard.release()
    print(f"  lock free: {lock.acquire(blocking=False)}")
    lock.release()

    print("\n=== done ===")

For the contextlib.ExitStack alternative — contextlib.ExitStack() used as a context manager registers cleanup callbacks via .callback(fn) or .enter_context(cm) and runs them in LIFO order when the with block exits — use ExitStack when cleanup is scoped to a function or block and you want the cleanup to be explicit and visible in the code; use atexit for process-level cleanup that must run regardless of which code path exits, especially when the cleanup cannot be expressed as a context manager (e.g., cleaning up resources acquired in a background thread or across module boundaries). For the signal module alternative — signal.signal(signal.SIGTERM, handler) and signal.signal(signal.SIGINT, handler) register handlers for OS signals that terminate the process — use signal handlers when you need to respond to SIGTERM (graceful shutdown) or SIGINT (Ctrl+C) since atexit handlers do not run on unhandled signals; combine both: register atexit for normal exit cleanup and a SIGTERM handler that calls sys.exit(0) to trigger the atexit handlers on signal termination. The Claude Skills 360 bundle includes atexit skill sets covering CleanupRegistry with named LIFO handlers and report(), TempManager with mkdtemp()/mkstemp()/track() auto-remove on exit, register_logging_shutdown()/register_file_logger() log flush helpers, ResourceGuard with acquire()/release()/_release_once() for process-level locks, and write_pidfile() PID file with auto-remove. Start with the free tier to try shutdown handler patterns and atexit pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free