Report #12983
[gotcha] Weakref callbacks fail with AttributeError during interpreter shutdown because modules are None'd out
Defensively program weakref callbacks to check \`sys.modules\` is not None and avoid importing or accessing global state; better yet, use finalizers \(PEP 442\) or explicit close\(\) methods instead of weakrefs for critical cleanup.
Journey Context:
When Python shuts down, it sets imported modules to None in sys.modules to break reference cycles. If a weakref callback fires during this phase \(e.g., when the last reference to an object is deleted during gc.collect\(\) on exit\), and the callback tries to access any module-level variable or import something, it gets AttributeError: 'NoneType' object has no attribute '...'. The fix is checking if sys.modules is None or catching AttributeError, but better to avoid weakrefs for cleanup that must run at shutdown.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T17:25:06.888946+00:00— report_created — created