news at manuelmgarcia.com
Thu Feb 13 22:55:54 CET 2003
On Thu, 13 Feb 2003 15:46:03 +0100, Roberto Cavada
<cavada at irst.itc.it> wrote:
>If I correctly understood, circular references detection is disabled
>when __del__ method is defined. I guess this is a precise choice, due
>to the fact that there is no control on what __del__ really does, so
>it is better wasting of memory than falling into segfaults.
You may be imagining the situation being worse than it really is.
Python's current garbage collection recognizes *all* circular
references that need garbage collection, no matter what.
If nothing in a particular circular reference has __del__ defined,
Python can delete them all in any order it wishes, and does so.
The *only* time a circular reference is not automatically deleted is
when one of the instances in the 'loop' has __del__ defined. This is
because the system does not know which reference link to break first.
Logically, it can choose to break any link in the circle to start, but
that choice might effect __del__ code, so your code would have
different behaviors depending on this arbitrary choice.
Python wants you to break the links yourself, so you can make a
deliberate choice where to start.
When Python needs help deleting circular references, all the instances
that participate in circular references get added to the list
gc.garbage. You can then scan through this list regularly, deleting
references between the instances in this list. When you delete all
the references, and then finially delete the instances from
gc.garbage, they disappear! And the __del__ code gets run at the
This is extra work, so you may want to think twice before adding a
__del__ method to something that might participate in a circular
Even with thousands of things being garbage collected, gc.garbage
might be a small list. In this case, you would just ignore it.
More information about the Python-list