[Tutor] Self-referential objects and garbage collection

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 20 Mar 2001 15:52:30 +0100


On Tue, Mar 20, 2001 at 07:54:24AM -0700, VanL wrote:
> How does Python deal with self-referential objects?  For example:
> 
> class DLinkedList:
> 
>     def __init__(self, name, objprev=None, objnext=None):
>         self.__label = name
>         if objprev: self.__prevlink = objprev
>         if objnext: self.__nextlink = objnext
>         else:
>             self.__prevlink = self
>             self.__nextlink = self
> 
> [methods snipped]
> 
> I had understood that Python used a reference-counting scheme.  Is
> this true, and is there a __destroy__ method to call for circular
> data structures?

Yes, Python uses reference counting, and this is a problem. Instead of
calling some sort of __destroy__ method, you must manually break the cycle,
ie set self.__prevlink and the other to None before you let go of the last
reference outside the object.

Since 2.0 there is an optional garbage collector that will find these
objects and clear them, but I don't have any experience with it yet, don't
even know if it's on by default (I don't think so). On Linux/Unix you must
give an option to ./configure when you compile Python to turn it on.

-- 
Remco Gerlich