new.instancemethod - how to port to Python3

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


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:

        ns = {}
        exec(code, ns)
        to_binary = ns['to_binary']
        self.to_binary = types.MethodType(to_binary, self)


-- 
Steven



More information about the Python-list mailing list