Problem with garbage collection (sort of)

Anand Pillai pythonguy at
Tue Aug 19 08:44:40 CEST 2003

The problem you are describing is one of 'cyclical'
references. This happens when obj A holds a reference
to obj B and obj B holds a reference to obj A.

 One way to work around this is to implement a global
registry object which stores all the objects in its
dictionary using names as keys. In your code you would
no longer need references to objects inside your classes
but just look them up from the global regsitry using
something like this.



Now since myobj is of local scope and not of class
scope (self...) python gc immmediately garbage collects
it. But the original object still remains active in the
global registry.

At the exit of your program write a hook to sys.exitfunc
which cleans up this global registry.

I had a similar problem in one of my projects and implemented
this using Alex Martelli's "borg" non-pattern. The code is
available in my harvestman project page at

I have not yet got around to testing the actual benefits
in gc I gained from this approach yet :-)


aahz at (Aahz) wrote in message news:<bhqo2b$rn6$1 at>...
> In article <246a4e07.0308180608.2b8d685a at>,
> Frank Millman <frank at> wrote:
> >
> >y is an instance of class c, which creates an instance of class b,
> >which creates an instance of class a. When y goes out of scope and is
> >deleted, I want the instances of class b and class a to be deleted as
> >well.
> Works for me in Python 2.2.3; what version are you using?

More information about the Python-list mailing list