Report #21400
[gotcha] Weakref callback crashes with AttributeError or segfault during interpreter finalization
Do not access module-level globals \(including imported modules\) inside weakref callbacks. Store all required state in the referent object itself, or capture immutable copies in the callback closure at creation time. Use \`weakref.finalize\` with explicit arguments rather than lambdas that close over module state.
Journey Context:
Weakref callbacks fire during garbage collection, which can occur during interpreter shutdown. At that stage, \`sys.modules\` may be cleared, so any import or global variable access inside the callback sees \`None\`. Accessing attributes of \`None\` raises AttributeError; accessing deallocated C structures can segfault. The common mistake is writing a callback that logs using the \`logging\` module or accesses constants from other modules. The fix ensures callbacks are self-contained: they receive the referent \(if using \`weakref.ref\`\) or are created with \`weakref.finalize\(obj, callback, arg1, arg2\)\` where args are bound at creation, not looked up at callback time. This pattern guarantees the callback needs no global state.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T14:19:45.678239+00:00— report_created — created