weak reference to bound method

Miles Kaufmann milesck at umich.edu
Fri Oct 2 05:59:42 EDT 2009


On Oct 2, 2009, at 1:54 AM, 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.

Like Peter said, bound methods are created on demand when they are  
obtained from the instance, not when the instance is created.

> Why does the weak reference claim that it is removed? And how can I  
> hold
> the reference to the method until the object is removed?

You could combine unbound methods with a weakref to the object:

r = weakref.ref(o)
MyClass.myfunc(r())

You could also create a wrapper object that holds a weak reference to  
the instance and creates a bound method on demand:

class WeakMethod(object):
     def __init__(self, bound_method):
         self.im_func = bound_method.im_func
         self.im_self = weakref.ref(bound_method.im_self)
         self.im_class = bound_method.im_class

     def __call__(self):
         obj = self.im_self()
         if obj is None: return None
         return types.MethodType(self.im_func, obj, self.im_class)
         # could alternately act like a callableproxy

-Miles




More information about the Python-list mailing list