Report #24922
[gotcha] AttributeError on module None in weakref callback during Python shutdown
In weakref callbacks, never assume imported modules or global variables exist. Access required modules via sys.modules.get\('modname'\) and check for None before use. Better yet, avoid weakref callbacks for critical cleanup; use context managers \(with statements\) or explicit close\(\) methods for deterministic resource management instead of relying on garbage collection.
Journey Context:
During interpreter shutdown, Python sets module globals to None in reverse order of import to break reference cycles and force garbage collection. If a weakref callback fires during this phase \(e.g., cleaning up a large object graph\), and the callback references any imported module \(logging, os, sys\), it finds the module object is None, leading to AttributeError. This is extremely difficult to reproduce because it depends on GC timing and shutdown order. The defensive pattern is to treat all module references in weakref callbacks as potentially None.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T20:14:31.625117+00:00— report_created — created