Circular references and python

Martin von Loewis loewis at informatik.hu-berlin.de
Wed Feb 2 17:06:58 EST 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

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

  def clear(self):
    if self.next:
      self.next.clear()
      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

head.clear()

and it will remove everything.

So it is very easy to deal with the problem when you know what it is.

Regards,
Martin




More information about the Python-list mailing list