pxd files
In addition to the .pyx
source files, Cython uses .pxd
fileswhich work like C header files – they contain Cython declarations(and sometimes code sections) which are only meant for inclusion byCython modules. A pxd
file is imported into a pyx
module byusing the cimport
keyword.
pxd
files have many use-cases:
They can be used for sharing external C declarations.
They can contain functions which are well suited for inlining by
the C compiler. Such functions should be markedinline
, example:
- cdef inline int int_min(int a, int b):
return b if b < a else aWhen accompanying an equally named
pyx
file, they
provide a Cython interface to the Cython module so that other
Cython modules can communicate with it using a more efficient
protocol than the Python one.
In our integration example, we might break it up into pxd
files like this:
Add a
cmath.pxd
function which defines the C functions available from
the Cmath.h
header file, likesin
. Then one would simply dofrom cmath cimport sin
inintegrate.pyx
.Add a
integrate.pxd
so that other modules written in Cython
can define fast custom functions to integrate.
- cdef class Function:
cpdef evaluate(self, double x)
cpdef integrate(Function f, double a,
double b, int N)Note that if you have a cdef class with attributes, the attributes must
be declared in the class declarationpxd
file (if you use one), not
thepyx
file. The compiler will tell you about this.