weak reference to bound method

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


Ole Streicher wrote:

> I am trying to use a weak reference to a bound method:
> 
> class MyClass(object):
>     def myfunc(self):
>         pass
> 
> o = MyClass()
> print o.myfunc
>>>>>   <bound method MyClass.myfunc of <__main__.MyClass object at
>>>>>   0xc675d0>>
> 
> import weakref
> r = weakref.ref(o.myfunc)
> print r()
>>>>>   None
> 
> This is what I do not understand. The object "o" is still alive, and
> 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
True
>>> id(a) == id(b)
False

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 
removed?

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?

Peter




More information about the Python-list mailing list