Python leaks in cyclic garbage collection

Chris Rebert clp2 at rebertia.com
Fri Feb 18 23:49:09 EST 2011


On Fri, Feb 18, 2011 at 8:10 PM, moerchendiser2k3
<googler.1.webmaster at spamgourmet.com> wrote:
> Hi, I have some problems with Python and the garbage collection. In
> the following piece of code I create a simple gargabe collection but I
> am still wondering why the finalizers are never called - at least on
> exit of Py they should be called somehow. What do I miss here?
<code snippet involving circularly-referenced objects with __del__
methods snipped>

Read The Fine Manual (all emphases added):

http://docs.python.org/reference/datamodel.html#object.__del__ :
"***It is not guaranteed that __del__() methods are called for objects
that still exist when the interpreter exits.***"
"Note: [...] x.__del__() — [...] is only called when x‘s reference
count reaches zero. Some common situations that may prevent the
reference count of an object from going to zero include: circular
references between objects [...] Circular references which are garbage
are detected when the option cycle detector is enabled (it’s on by
default), ***but can only be cleaned up if there are no Python-level
__del__() methods involved***. Refer to the documentation for the `gc`
module for more information about how __del__() methods are handled by
the cycle detector, particularly the description of the `garbage`
value."

And following the pointer to gc.garbage's docs:
http://docs.python.org/library/gc.html#gc.garbage :
"Objects that have __del__() methods and are part of a reference cycle
***cause the entire reference cycle to be uncollectable*** [...]
Python doesn’t collect such cycles automatically because, in general,
it isn’t possible for Python to guess a safe order in which to run the
__del__() methods. [...] It’s generally better to avoid the issue by
not creating cycles containing objects with __del__() methods"

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list