new.instancemethod - how to port to Python3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Apr 7 06:52:11 EDT 2013


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.


> ----
> 
> The last line has been transformed to
>     return self.to_binary(*varargs, **keys)
> 
> by  2to3
> 
> But how to transform the line with new.instancemethod. I've seen
> examples where
> new.instancemethod(to_binary, ....)
> is replaced by  to_binay
> but this doesn't work here since to_binary isn't known.

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?




-- 
Steven



More information about the Python-list mailing list