Newby: Howto declare staticmethod in cdef class

719 views
Skip to first unread message

t.k...@online.de

unread,
Sep 30, 2011, 9:16:40 AM9/30/11
to cython-users
Hello,

I play around with cython for a few days now. I have many questions,
although i read the tutorials on http://docs.cython.org/.

Maybe someone can help me with this specific problem:
I have:

class Interface(object):
map = {1000:None}
epsilon = 1e-10

def __init__(self, int id):
self.id = id
Interface.map[id] = self

def __call__(self, double x):
raise NotImplementedError

def derivative(self, double x):
return (self(x + self.epsilon) - self(x)) / self.epsilon

@staticmethod
def next_free_id():
return max(Interface.map.keys())+1

and many subclasses which do mathematical stuff, for example

class Scale(Interface):

def __init__(self, double scale, int id=Interface.next_free_id()):
self.scale = scale
super(Scale,self).__init__(id)

def __call__(self, double x):
return x*self.scale

def derivative(self, double x):
return self.scale

As you can see, I already added static types. But cython -a shows me
that (I think because of the self.scale in this case) the code cannot
be translated into pure C.

First question:
To static type the members (like self.scale) I need to transform the
class Scale into cdef class Scale,
and class Interface to cdef class Interface ?

Second question:
How can I declare a staticmethod in the cdef class Interface? (If a
try i get an error "Cdef functions/classes cannot take arbitrary
decorators.")

I would be glad if someone could outline howto correctly transform the
above python example into fast cython code.

Thank you

Thomas

Robert Bradshaw

unread,
Sep 30, 2011, 1:37:03 PM9/30/11
to cython...@googlegroups.com

Cython uses the Python library to create classes, it will never be
pure C. (But it still can be very fast).

> First question:
> To static type the members (like self.scale) I need to transform the
> class Scale into cdef class Scale,
> and class Interface to cdef class Interface ?

Yes, that could help a lot.

> Second question:
> How can I declare a staticmethod in the cdef class Interface? (If a
> try i get an error "Cdef functions/classes cannot take arbitrary
> decorators.")
>
> I would be glad if someone could outline howto correctly transform the
> above python example into fast cython code.

Though it's not as clean, a quick way to do it would be to pull the
static members and methods out to cdef'd module-level members and
methods. (Fast support for static class members and methods is
something we'd like to have, but it's not there yet.)

- Robert

Reply all
Reply to author
Forward
0 new messages