python 3 problem: how to convert an extension method into a class Method

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 26 23:46:04 EST 2013


On Tue, 26 Feb 2013 17:21:16 +0000, Robin Becker wrote:

> In python 2 I was able to improve speed of reportlab using a C extension
> to optimize some heavily used methods.
> 
> so I was able to do this
> 
> 
> class A:
>      .....
>      def method(self,...):
>         ....
> 
> 
> try:
>      from extension import c_method
>      import new
>      A.method = new.instancemethod(c_method,None,A)
> except:
>      pass

Why are you suppressing and ignoring arbitrary errors here? That doesn't 
sound good. Surely a better way would be:

import new
try:
    from extension import c_method
except ImportError:
    pass
else:
    A.method = new.instancemethod(c_method, None, A)



> and if the try succeeds our method is bound as a class method ie is
> unbound and works fine when I call it.
> 
> In python 3 this doesn't seem to work at all. In fact the new module is
> gone. The types.MethodType stuff doesn't seem to work.

I've never tried this with a function written in C, but for one written 
in Python all you need is this:

A.method = c_method


Try that and see if it works with your function written in C. I expect 
that it will, provided that the function is written as a method 
descriptor. I don't know enough about C extensions to tell you how to do 
that, sorry.



-- 
Steven



More information about the Python-list mailing list