I am writing a cython module that provides several extension types that use optimized cdef
functions. Several of these extension types (about 10, each containing about 200 lines of code) have exactly the same structure but don't call the same cdef
functions. I would like to factorize my module so that only one extension type can handle all the different configurations I need.
To make this clearer, here is a (very silly) example of the structure of the module I'm writing :
cdef class A1:
cdef double x
def __init__(self, double x):
self.x = x
def apply(self):
self.x = f1(self.x)
cdef class A2:
cdef double x
def __init__(self, double x):
self.x = x
def apply(self):
self.x = f2(self.x)
cdef double f1(double x):
return x**1
cdef double f2(double x):
return x**2
...
and the kind of factorized code I would like to obtain :
cdef class A:
cdef int n
cdef double x
def __init__(self, double x, int n):
self.x = x
self.f = globals()[f'f{n}']
def apply(self):
self.x = self.f(self.x)
In pure Python, this kind of structure is easy to setup using globals
or getattr
, but in cython cdef
objects are (of course) not accessible from python, so not in globals()
.
I guess that a C
implementation of this kind of code would use function pointers but I can't find how to do this inside an cython extension type. Actually the real question is 'is it possible to add a pointer to a cdef function as an instance attribute (in self) ? If not, how can I factorize this kind of code without losing performances (i.e. without changing my cdef functions) ?