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

Dave Angel davea at davea.name
Tue Feb 26 12:52:30 EST 2013


On 02/26/2013 12:21 PM, 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:

That creates an old-style class in  Python 2.x.  They've been obsolete 
for many years.  You want to derive from object:
     class  A(object):

Once you do, Python 2 and Python 3 should work the same.  I can't help 
with the rest, unfortunately.

>      .....
>      def method(self,...):
>         ....
>
>
> try:
>      from extension import c_method
>      import new
>      A.method = new.instancemethod(c_method,None,A)
> except:
>      pass
>
> 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.
>
> Is there a way in Python 3.3 to make this happen? This particular method
> is short, but is called many times so adding python wrapping layers is
> not a good way forward.
>
> If the above cannot be made to work (another great victory for Python 3)
> then is there a way to bind an external method to the instance without
> incurring too much overhead.
>
> Alternatively could it make sense to implement an accelerated basetype
> that just contains the accelerated methods of class A. I could then
> imagine doing something like
>
> try:
>      from extension import class c_baseA as baseA
> except:
>      class baseA:
>         def method(....)
>
> class A(baseA):
>      .....
>
> presumably I then get some kind of penalty for the base class lookup,
> but how bad is that?


-- 
DaveA



More information about the Python-list mailing list