Report #12582
[gotcha] weakref callbacks accessing globals raise AttributeError during Python interpreter shutdown
Use weakref.finalize\(\) instead of weakref.ref\(callback=...\) for cleanup actions. Bind required state as default arguments or closure variables in the finalizer function to avoid accessing global modules \(sys, os, etc.\) that may already be None during shutdown.
Journey Context:
Developers use weak references to avoid circular dependencies and ensure cleanup of external resources \(file handles, C library bindings\). The callback registered with weakref.ref executes when the referent dies, but if this occurs during interpreter teardown, Python has already set imported modules to None in sys.modules. Accessing 'os.close\(fd\)' in the callback raises 'AttributeError: 'NoneType' object has no attribute 'close''. weakref.finalize was introduced specifically to handle this by registering with the atexit machinery and capturing necessary state at registration time, making the callback robust against module teardown.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T16:20:39.655595+00:00— report_created — created