Circular reference problem -- advice?

Thomas Wouters thomas at xs4all.net
Mon Jul 10 15:38:51 EDT 2000


On Mon, Jul 10, 2000 at 12:06:46PM -0700, Erik Max Francis wrote:

> I've come across a problem due to circular references, and I'm not sure
> what's the best way to tackle it.  In essence, the problem is that I
> need a particular class to keep an associative array of its methods for
> a lookup table (it's essentially a dispatcher).  But with references to
> its own bound methods, Python's garbage collector concludes it has
> circular references and thus its destructor never gets called.

> For the application I need, it's imperative that the destructor get
> called.  What is the best way to solve this?  I can think of a few:

> - Move the map to a local variable in the dispatching function
> - Make map a lookup table of _unbound_ methods
> - Build a string of the function call and then exec it

Instead of calling exec, you're better off calling 'apply':

apply(self, method, args)

(where 'method' is a string containing the method name, and args is a tuple
(or other sequence) containing the desired arguments.

Alternatively, you can keep the current setup, and manually break the
circular reference before you delete the last reference to the object. You
can sometimes do this automatically by using a container object (one that
*doesn't* have a cirulcar reference ;) that has a __del__ that breaks the
cirulcar reference.

> What would be the most effective way of getting around this?  I'm
> thinking that using unbound methods would probably be the best way.

You can use self.__class__.__dict__ as a convenient index to attributes on
the class, and then 'apply(self, method, args)' to call the bound variants
of those. No circular references involved, though it might not fit your
need.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list