Report #39687
[gotcha] Objects with \_\_del\_\_ in reference cycles are not garbage collected
Do not use \_\_del\_\_ for resource cleanup; use context managers \(with statement\) or weakref.finalize. If you must use \_\_del\_\_, avoid creating reference cycles involving the object, or use weak references to break the cycle.
Journey Context:
Python's cyclic garbage collector cannot collect objects in reference cycles \(A↔B\) if any object in the cycle defines \_\_del\_\_, because it cannot determine a safe destruction order \(A's destructor might need B, but B's destructor might need A\). These objects are either leaked indefinitely or moved to gc.garbage, and their \_\_del\_\_ methods never run, causing resource leaks \(file handles, sockets, memory\). This is particularly insidious in large applications where 'cleanup' logic in \_\_del\_\_ never executes due to accidental cycles. The weakref.finalize API was specifically introduced to register cleanup callbacks without creating the reference-counting issues of \_\_del\_\_, and it works even if the object is part of a cycle. The context manager protocol is the idiomatic replacement for deterministic cleanup.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:05:25.993896+00:00— report_created — created