Right now, the presence of __del__ method prevents cycles from being collected.  It is possible for an application to rummage through gc.garbage and break links between objects.  However, for a large application this may be inefficient or inelegant for several reasons:<br>
<br>- It may be most natural to break the links on objects of type Foo, even though Foo is a minority of items (e.g., if Foo is parent node with many children).<br><br>- It's difficult to know how frequently to sift through the garbage<br>
<br>- Third-party package may create noncollectable garbage that we need to sift through, even though we don't know how to safely break links on their objects.<br><br>- If every package sifts through the garbage independently, there's a lot of extra work going on.<br>
<br>I propose the following simple solution.  When the garbage collector is about to add an object to gc.garbage, it checks to see if the object has a __clear__ method.  If so, the garbage collector calls it, giving the object an opportunity to safely break any cycles it may be in.  If it breaks the cycles, great!  The object can now safely be collected and __del__ will eventually be called.  If not, then the object gets added to gc.garbage after all and no harm is done.<br>
<br>It would be simple to implement, efficient, and the cognitive load for the programmer using __del__ and __clear__ is small.<br><br>Thoughts?<br><blockquote style="margin: 1.5em 0pt;">--<br>
Daniel Stutzbach, Ph.D.<br>
President, <a href="http://stutzbachenterprises.com">Stutzbach Enterprises, LLC</a>
</blockquote>