Circular references and python

Martin von Loewis loewis at
Wed Feb 2 17:06:58 EST 2000

"Brian Dam Pedersen" <brian.pedersen at> 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

class ListItem:
  def __init__(self,next,prev):
    self.prev, = 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

  def clear(self):
    if  # 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 mailing list