from weakref import proxy
from types import MethodType
class weakmethod(object):
__slots__ = ["func"]
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
if obj is not None:
obj = proxy(obj)
return MethodType(self.func, obj, cls)
#######################################################
>>> class Foo(object):
... @weakmethod
... def bar(self, a, b):
... print self, a, b
...
>>> f = Foo()
>>> b = f.bar
>>> b
>
>>> b(1, 2)
<__main__.Foo object at 0x009FC070> 1 2
>>> del f
>>> b
>
>>> b(1,2)
Traceback (most recent call last):
File "", line 1, in
File "", line 4, in bar
ReferenceError: weakly-referenced object no longer exists