[Python-3000] weakrefs of bound methods

Nick Craig-Wood nick at craig-wood.com
Fri Feb 15 11:12:19 CET 2008


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.

or

2) throw an exception when you attempt to take a weak reference of a
bound method?  Maybe only when it has a single refcount?

Eg

  Python 3.0a2+ (py3k:60831, Feb 15 2008, 09:52:40)
  [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  >>> from weakref import WeakKeyDictionary
  >>> d=WeakKeyDictionary()
  >>> class A(object):
  ...     def f(self): print("hello")
  ...
  >>> a=A()
  >>> a.f()
  hello
  >>> d[a.f] = True
  >>> d.keys()
  []
  >>> 

I know how to work around the problem.  The fact that it passes
completely silently uses up lots of developer time debugging it
though!

Thanks!
-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick


More information about the Python-3000 mailing list