[Python-ideas] breaking cycles that include __del__

Daniel Stutzbach daniel at stutzbachenterprises.com
Sat Oct 17 16:34:46 CEST 2009


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:

- 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).

- It's difficult to know how frequently to sift through the garbage

- 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.

- If every package sifts through the garbage independently, there's a lot of
extra work going on.

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.

It would be simple to implement, efficient, and the cognitive load for the
programmer using __del__ and __clear__ is small.

Thoughts?

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091017/55f60e86/attachment.html>


More information about the Python-ideas mailing list