Using weakrefs instead of __del__

Greg Ewing greg at cosc.canterbury.ac.nz
Thu Apr 7 23:30:03 EDT 2005


Rhamphoryncus wrote:
> class RealFoo:
>   refs = set()
>   def __init__(self, front):
>     self.refs.add(weakref.ref(front, self.cleanup))
>   def blah(self):
>     print "Blah!"
>   def cleanup(self, ref):
>     print "Doing cleanup"
>     self.refs.remove(ref)

That won't work, because the bound method you're using as
the cleanup function contains a reference to the object,
preventing it from being deallocated.

The weakref callback is only called *after* the object has
been deallocated. If you try to contrive a way of passing the
object to the callback, you will just end up keeping it alive.
To use a weakref as a finalizer, the information needed
for finalization needs to be kept somewhere outside of
the object triggering the finalization.

This may be what you were trying to achieve by separating
your object into a Foo and a RealFoo. If that's so, you
should have made the weak ref point to the Foo, not the
RealFoo.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list