Skip to content

Instantly share code, notes, and snippets.

@teepark
Created May 17, 2011 20:26
Show Gist options
  • Save teepark/977305 to your computer and use it in GitHub Desktop.
Save teepark/977305 to your computer and use it in GitHub Desktop.
class WeakMethodRef(object):
def __init__(self, method):
if getattr(method, "im_self", None):
self.obj = weakref.ref(method.im_self)
elif getattr(method, "im_class", None):
self.obj = weakref.ref(method.im_class)
else:
self.obj = None
if getattr(method, "im_func", None):
method = method.im_func
self.func = weakref.ref(method)
def __nonzero__(self):
if self.obj is not None and not self.obj():
return False
return self.func() is not None
def __call__(self, *args, **kwargs):
if not self:
raise Exception("weakrefs broken")
if self.obj is not None:
args = (self.obj(),) + args
return self.func()(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment