By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,767 Members | 1,357 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,767 IT Pros & Developers. It's quick & easy.

Using weakrefs instead of __del__

P: n/a
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

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.