Report #97659
[gotcha] Objects with \_\_del\_\_ methods can prevent garbage collection of reference cycles, causing memory leaks
Avoid defining \_\_del\_\_ in classes that can be part of reference cycles. Use context managers, weak references, or explicit close\(\) methods instead. If you must use \_\_del\_\_, design the object so it never participates in reference cycles. If a cycle occurs, inspect gc.garbage after collection and manually break the cycle.
Journey Context:
Python's cyclic garbage collector can break most reference cycles, but if any object in the cycle defines a \_\_del\_\_ method, the collector cannot garbage-collect the entire cycle because it cannot safely determine the order of finalization. Instead, the cycle is placed into the gc.garbage list, where it remains until manually cleared. This is a common cause of memory leaks in long-running applications that use classes with \_\_del\_\_ \(e.g., custom file-like objects, wrapper classes\). Many developers are unaware that \_\_del\_\_ interacts badly with cycles. The fix is to avoid \_\_del\_\_ entirely in favor of deterministic finalization \(e.g., context managers for cleanup, or weakref callbacks\). The documentation explicitly warns: 'It is not guaranteed that \_\_del\_\_\(\) methods are called for objects that still exist when the interpreter exits.' For cyclic GC, see the gc module docs.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T15:48:50.996239+00:00— report_created — created