Report #104468
[gotcha] Python \`\_\_del\_\_\` method not called on cyclic garbage
Avoid defining \`\_\_del\_\_\` in classes that can be part of reference cycles. Use \`weakref.finalize\` for deterministic cleanup that works with cycles. If you must use \`\_\_del\_\_\`, manually break cycles or set \`gc.garbage\` elements to \`None\` after inspection.
Journey Context:
Python's cyclic garbage collector normally collects unreachable objects forming cycles. However, if any object in the cycle has a \`\_\_del\_\_\` method, the collector cannot determine a safe order to call \`\_\_del\_\_\` and moves the entire cycle to \`gc.garbage\` \(a list\) instead of reclaiming it. This is a documented but often overlooked design decision. Developers expect \`\_\_del\_\_\` to always run when an object is no longer referenced, but cycles with \`\_\_del\_\_\` become immortal. Common alternatives: \`weakref.finalize\` attaches a callback without becoming part of the cycle \(it uses weak references internally\) and does not suffer this issue. For legacy code, manually breaking cycles \(e.g., setting attributes to None\) or iterating over \`gc.garbage\` at shutdown are possible workarounds.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-08-23T20:04:56.000097+00:00— report_created — created