no unbound methods in py3k
Thomas Heller
theller at python.net
Wed Oct 8 15:56:12 EDT 2008
I'm currently using code like this to create unbound methods
from functions and stick them into classes:
method = new.instancemethod(raw_func, None, cls)
setattr(cls, name, method)
Ok, python 2.6, run with the -3 flag, gives a warning that the new
module is going away in python 3.0, so the equivalent code is:
method = types.MethodType(raw_func, None, cls)
setattr(cls, name, method)
However, this code will not work in Python 3.0 because there are
no unbound methods any longer. The only way that I found so far
is this code:
method = lambda self, *args: raw_func(self, *args)
setattr(cls, name, method)
or the equivalent:
def method(self, *args):
return raw_func(self, *args)
setattr(cls, name, method)
but this is very ugly, imo. Is there another way?
The raw_func instances that I have are not descriptors (they
do not implement a __get__() method...)
Thanks,
Thomas
More information about the Python-list
mailing list