Using weakrefs instead of __del__

Rhamphoryncus rhamph at gmail.com
Wed Apr 6 13:20:16 EDT 2005


I know __del__ can't be relied on to do cleanup, so I'm thinking of
using a globally reachable weakref to do the job, like so:

import weakref

class Foo:
  def __init__(self, *args, **kwargs):
    self.__realfoo = RealFoo(self, *args, **kwargs)
  def blah(self):
    return self.__realfoo.blah()

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)

Is there any reason why this wouldn't work?  Can it be used as a
general replacement for anything that needs __del__?  Even in Jython or
other alternative implementations?

Some issues I know about:
 * The weakref must be globally reachable (as I do with the above code)
to make sure it doesn't get deleted at the same time Foo does, because
python would not call the callback if that were the case.
 * I can't use any getattr tricks to wrap .blah() because Foo().blah()
would only use a  method bound to RealFoo, thus allowing Foo to be
deallocated and .cleanup() to be called before the method itself is.
Unfortunately my metaclass-fu is too weak to figure out something
without that problem.
 * I've no idea what will happen when the interpreter exits, but I
don't imagine it would matter much for most uses.

--
Adam Olsen, aka Rhamphoryncus




More information about the Python-list mailing list