Extending Python: rewriting a single method in C

Alexander Gavrilov agavrilov at home.com
Mon Mar 12 21:19:42 EST 2001


"Jeff Epler" <jepler at inetnebr.com> wrote in message
news:slrn9apn8f.382.jepler at potty.housenet...
> On 12 Mar 2001 11:13:51 +0000, Jacek Generowicz
>  <jmg at ecs.soton.ac.uk> wrote:
> >I have an object-oriented numerical code written in Python. It has
> >come to the stage where the speed of the code is seriously impeding
> >progress. Profiling reveals (surprise, surprise) that most of the time
> >is spent in only 2 methods.
> >
> >Is there any way of re-writing just these methods in C ?
>
> It's easy to write a function in C.  Other posters have mentioned
references
> to documentation about doing this.
>
> However, you cannot make a builtin function be a method of a
class/instance.
> Instead, you could write:
>
> from cmodule import fast_a, fast_b
>
> class fastKlass(Klass):
> def a(self, int1, int2):
> fast_a(self, int1, int2)
> def b(self, int1, int2):
> fast_b(self, int1, int2)
>

Actually, you can write the following:

class fastKlass(Klass):
    a = fast_a
    b = fast_b

Whenever the program calls 'a' or 'b' methods, 'fast_a' or 'fast_b' get
called instead. And you'll eliminate of 'double-calling' overhead.
I didn't check it with functions from C extension module, but it works with
plain Python functions. The following example works for me:

def func1(self):
    print self.a1

def func2(self,somearg):
    print somearg+self.a2

class C:
    def __init__(self):
        self.a1 = 'attr1'
        self.a2 = 'attr2'

    meth1 = func1
    meth2 = func2

c = C()
c.meth1()
c.meth2('Some string ')

Alexander





More information about the Python-list mailing list