Problem with garbage collection (sort of)

Anand Pillai pythonguy at Hotpop.com
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.

myobj=myglobals.lookup('myobject')
myobj.performsomeaction() 

...

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 
http://members.lycos.co.uk/anandpillai

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

-Anand


aahz at pythoncraft.com (Aahz) wrote in message news:<bhqo2b$rn6$1 at panix2.panix.com>...
> In article <246a4e07.0308180608.2b8d685a at posting.google.com>,
> Frank Millman <frank at chagford.com> 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