[Python-3000] weakrefs of bound methods

Phillip J. Eby pje at telecommunity.com
Fri Feb 15 19:26:21 CET 2008


At 09:35 AM 2/15/2008 -0800, Guido van Rossum wrote:
>On Fri, Feb 15, 2008 at 2:12 AM, Nick Craig-Wood <nick at craig-wood.com> wrote:
> > I've just been bitten yet again by the fact you can't have a weakref
> >  to a bound method!  I find myself wanting to do this whenever I have a
> >  registry of callback functions.
> >
> >  Could we in py3k either
> >
> >  1) make weakrefs to bound methods work?  A weakref to a bound method
> >  should mean hold the weakref on the instance and bind the method at
> >  the last moment.
>
>I think you're somehow confused about how weakrefs are supposed to
>work. They work fine!

The use case here is actually to keep the callback around only so 
long as the object exists.

There are various ways to do this, of course, that don't require 
changing the language or stdlib.  One of the simplest (for 2.4 and 
up) is to create a callable weakref subclass that emulates a bound 
method.  Another is to create a bound method whose im_self is a weakref proxy.

I've never actually encountered a usecase for keeping a standard 
weakref to a standard bound method, though.  It's pretty useless, 
because bound methods are nearly always immediately disposed of, and 
there's no logical place (or reason) to store them.  So, Nick's query 
is (in effect), can we either:

1. make ref(method) create a "weak method" instead, or

2. make ref(method) an error instead of useless behavior that gives 
you the illusion of working code



More information about the Python-3000 mailing list