Circular references and python
Martin von Loewis
loewis at informatik.hu-berlin.de
Wed Feb 2 23:06:58 CET 2000
"Brian Dam Pedersen" <brian.pedersen at mail.danbbs.dk> writes:
> Now the lists are circular referenced, and dereferencing them will
> not garbage-collect them. To break up the chain just do
The essential piece here is that you have to break the circularity
with explicit code; Python will then clean-up the rest when you drop
the last reference to the structure.
Since cyclic structures are usually regular in some way, it is often
easy to break the cycles with a recursive algorithm. Consider
self.prev,self.next = prev,next
This could be used in a double-linked list (not that a double-linked
list is particular useful in Python :-). To allow breaking the cycles,
you can do
self.next=None # or self.prev=None
If you know you don't need such a list (stored in a variable head)
anymore, you do
and it will remove everything.
So it is very easy to deal with the problem when you know what it is.
More information about the Python-list