[Python-3000] weakrefs of bound methods
Guido van Rossum
guido at python.org
Fri Feb 15 20:41:14 CET 2008
On Fri, Feb 15, 2008 at 10:26 AM, Phillip J. Eby <pje at telecommunity.com> wrote:
> 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.
Ah, I see. Nick actually wrote this but because I'm so familiar with
the concept of a bound method object I didn't see what his actual
issue was. Sorry Nick!
> 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
#2 is easily implemented (just remove the machinery to support weak
refs from the bound method object) but the question is, will it break
anybody's code -- and if so, do we care enough to break it? (In Py3k,
#1 isn't so easy in terms of how you'd implement it -- I don't think
the weakref.ref() call currently has a way to customize what kind of
thing you get back. I'd be open for a patch containing working code
that can be generalized to other cases.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000