Report #41521
[gotcha] \_\_del\_\_ finalizer fails with AttributeError during interpreter shutdown or prevents GC of cycles
Avoid \`\_\_del\_\_\` entirely; use context managers \(\`with\` statements\) for deterministic cleanup or \`weakref.finalize\` which does not resurrect objects and handles shutdown ordering safely.
Journey Context:
Implementing \`\_\_del\_\_\` appears to offer C\+\+-style RAII destructors, but CPython's garbage collector imposes two lethal constraints. First, if an object with \`\_\_del\_\_\` participates in a reference cycle, the cyclic GC cannot break the cycle because it cannot determine a safe destruction order; the objects leak until cyclic GC runs with a heuristic \(and in some cases, they persist forever\). Second, during interpreter shutdown, module globals are set to \`None\` before \`\_\_del\_\_\` methods run. If your finalizer references \`os.remove\` or \`open\`, it raises \`AttributeError: 'NoneType' object has no attribute 'remove'\` because the \`os\` module is already torn down. \`weakref.finalize\` avoids both issues: it registers a callback without binding the object lifetime, bypasses resurrection problems, and ensures module references are captured at registration time, not shutdown.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T00:10:04.506789+00:00— report_created — created