Report #39501
[gotcha] atexit registered functions fail accessing imported modules during interpreter shutdown
Capture required module references in the function's closure at registration time \(e.g., \`os=os\`\), or use \`weakref.finalize\` with the object and state encapsulated instead of atexit
Journey Context:
During interpreter shutdown, Python aggressively nulls out module globals in sys.modules in reverse import order. If your atexit handler was registered early but depends on a module imported later \(like \`os\`, \`sys\`, or \`logging\`\), that module may be None when your handler runs, raising AttributeError. This is silent and deadly because it happens during shutdown when exception handling is fragile. The common fix of importing inside the function fails because the module object itself is gone. You must bind the module to a local variable in the closure at registration time, or avoid atexit entirely in favor of weakref finalizers which run before module teardown.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T20:46:39.500838+00:00— report_created — created