The untimely dimise of a weak-reference

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Jul 30 23:11:30 EDT 2010


Vincent van Beveren wrote:

> I was working with weak references in Python, and noticed that it 
 > was impossible to create a weak-reference of bound methods.

 > is there anything I can do about it?

You can create your own wrapper that keeps a weak reference to
the underlying object. Here's an example.

import weakref

class weakmethod(object):

   def __init__(self, bm):
     self.ref = weakref.ref(bm.im_self)
     self.func = bm.im_func

   def __call__(self, *args, **kwds):
     obj = self.ref()
     if obj is None:
       raise ValueError("Calling dead weak method")
     self.func(obj, *args, **kwds)

if __name__ == "__main__":

   class A(object):

     def foo(self):
       print "foo method called on", self

   a = A()
   m = weakmethod(a.foo)
   m()
   del a
   m()



More information about the Python-list mailing list