new.instancemethod - how to port to Python3
Helmut Jarausch
jarausch at skynet.be
Sun Apr 7 11:35:54 EDT 2013
On Sun, 07 Apr 2013 11:07:07 +0000, Steven D'Aprano wrote:
> On Sun, 07 Apr 2013 10:54:46 +0000, Helmut Jarausch wrote:
>
>> class Foo :
>> ....
>> def to_binary(self, *varargs, **keys):
>> ....
>> code= ...
>> args= ...
>> # Add function header
>> code = 'def to_binary(self, %s):\n' % ', '.join(args) + code
>> exec(code)
>> self.to_binary = new.instancemethod(to_binary, self,
>> self.__class__)
>> return self.to_binary(*varargs, **keys)
>
>
> Self-modifying code! Yuck!
>
> Nevertheless, try changing the line with new.instancemethod to this:
>
> self.to_binary = types.MethodType(to_binary, self)
>
>
> and see if it works. If it complains about the call to exec, then change
> that part of the code to this:
Thanks, that worked
>
> ns = {}
> exec(code, ns)
I just had to replace this with
exec(code,globals(),ns)
> to_binary = ns['to_binary']
> self.to_binary = types.MethodType(to_binary, self)
Helmut
More information about the Python-list
mailing list