weak reference to bound method

Peter Otten __peter__ at web.de
Fri Oct 2 11:33:52 CEST 2009

Ole Streicher wrote:

> class MyClass(object):
>     def myfunc(self):
>         pass
> o = MyClass()
> print o.myfunc
>>>>>   0xc675d0>>
> import weakref
> r = weakref.ref(o.myfunc)
> print r()
>>>>>   None
> therefore the bound method "o.myfunc" shall exists.

No. o.myfunc is a different object, a bound method, and every time you 
access o's myfunc attribute a new bound method is created:

>>> class MyClass(object):
...     def myfunc(self):
...             pass
>>> o = MyClass()
>>> a = o.myfunc
>>> b = o.myfunc
>>> a == b

The bound method holds references to the instance and the function, not the 
other way around:

>>> a.im_class, a.im_self, a.im_func
(<class '__main__.MyClass'>, <__main__.MyClass object at 0x7f1437146710>, 
<function myfunc at 0x7f14371318c0>)

> Why does the weak reference claim that it is removed? 

Because there are indeed no more strong references to the bound method.

> And how can I hold the reference to the method until the object is 

If you kept a strong reference to the bound method it would in turn keep the 
MyClass instance alive. Maybe you could store the bound method in the 
instance and rely on cyclic garbage collection.

Is there an actual use case?


More information about the Python-list mailing list