From: Gregory Ewing on
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()
From: Vincent van Beveren on
Hi Gregory,


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

Thanks for the code!

Regards,
Vincent

From: Vincent van Beveren on
Hi Christiaan,



> Instances of a class have no means of storing the bound method object.
> The or unbound bound method is a simple and small wrapper that keeps a
> reference to the class, "self" and the function object. Python keeps a
> pool of empty method objects in a free list. The creation of a new bound
> method just takes a few pointer assignments and three INCREFs.

Okay, that also explains the consistent memory assignment. Maybe I'll create a bound-method caching object, see how slow/fast it is in comparison, and see what ever other issues I run into.

Regards,
Vincent


-----Original Message-----
From: python-list-bounces+v.vanbeveren=rijnhuizen.nl(a)python.org [mailto:python-list-bounces+v.vanbeveren=rijnhuizen.nl(a)python.org] On Behalf Of Christian Heimes
Sent: vrijdag 30 juli 2010 16:44
To: python-list(a)python.org
Subject: Re: The untimely dimise of a weak-reference

Am 30.07.2010 16:06, schrieb Vincent van Beveren:
> I did not know the object did not keep track of its bound methods. What advantage is there in creating a new bound method object each time its referenced? It seems kind of expensive.
Christian

--
http://mail.python.org/mailman/listinfo/python-list
From: Bruno Desthuilliers on
Gregory Ewing a écrit :
(snip)

> 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)

Would be better with :

return self.func(obj, *args, *kwds)

From: Gregory Ewing on
Bruno Desthuilliers wrote:

> Would be better with :
>
> return self.func(obj, *args, *kwds)

Thanks -- well spotted!

--
Greg