Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #39984 > unrolled thread

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

Started byPeter Otten <__peter__@web.de>
First post2013-02-26 19:38 +0100
Last post2013-02-26 19:38 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: python 3 problem: how to convert an extension method into a class Method Peter Otten <__peter__@web.de> - 2013-02-26 19:38 +0100

#39984 — Re: python 3 problem: how to convert an extension method into a class Method

FromPeter Otten <__peter__@web.de>
Date2013-02-26 19:38 +0100
SubjectRe: python 3 problem: how to convert an extension method into a class Method
Message-ID<mailman.2562.1361903928.2939.python-list@python.org>
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
> 
> 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.

Hm, according to my random measurement your clever approach incurs more 
overhead than the straight-forward way that continues to work in Python 3:

$ python -m timeit -s 'from new import instancemethod
> from math import sqrt
> class A(int): pass
> A.m = instancemethod(sqrt, None, A)
> a = A(42)
> ' 'a.m()'
1000000 loops, best of 3: 0.5 usec per loop
$ python -m timeit -s 'from math import sqrt
> class A(int):
>     def m(self):
>         return sqrt(self)
> a = A(42)
> ' 'a.m()'
1000000 loops, best of 3: 0.473 usec per loop

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web