Created
May 17, 2011 20:26
-
-
Save teepark/977305 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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