new.instancemethod - how to port to Python3

Helmut Jarausch jarausch at skynet.be
Sun Apr 7 11:37:13 EDT 2013


On Sun, 07 Apr 2013 10:52:11 +0000, Steven D'Aprano wrote:

> On Sun, 07 Apr 2013 09:50:35 +0000, Helmut Jarausch wrote:
> 
>> Hi,
>> 
>> I'm trying to port a class to Python3.3 which contains
>> 
>> class  Foo :
>>     ....
>>     def to_binary(self, *varargs, **keys):
>>        ....
>>     ....
>>     self.to_binary = new.instancemethod(to_binary, self, self.__class__)
>>     # Finally call it manually
>>     return apply(self.to_binary, varargs, keys)
> 
> 
> I do not understand this code. Can you give a short example that actually 
> works please?
> 
> As written, your code has a class that defines a to_binary method. Then, 
> *outside* of the method, in the class definition, you refer to "self", 
> and use a return statement. This is not possible -- self does not exist, 
> and return gives a SyntaxError.
> 
> But, if the indentation is wrong, it looks like you are trying to get the 
> to_binary method to replace itself with a global to_binary function. I do 
> not understand this.

Sorry, the first excerpt was to too short.
As noted in the reply to Arnaud, a better excerpt is:

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)

If you'd like to see the full code (not by me)
please see the Python package http://python-xlib.sourceforge.net/
file Xlib/protocol/rq.py   method to_binary in class Struct
> 
> I cannot answer your question, because I don't understand it. But perhaps 
> this will help:
> 
> 
> # === Python 2 version ===
> class Spam:
>     pass
> 
> x = Spam()
> 
> def method(self, arg):
>     return {arg: self}
> 
> import new
> x.method = new.instancemethod(method, x, x.__class__)
> 
> x.method("hello")
> => returns {'hello': <__main__.Spam instance at 0xa18bb4c>}
> 
> 
> Here is the Python 3 version:
> 
> 
> # === Python 3 ===
> class Spam:
>     pass
> 
> x = Spam()
> 
> def method(self, arg):
>     return {arg: self}
> 
> import types
> x.method = types.MethodType(method, x)
> 
> x.method("hello")
> => returns {'hello': <__main__.Spam object at 0xb7bc59ac>}
> 
> 
> 
> Does this help?

Yes, 




More information about the Python-list mailing list