5.3.3 Using cdef Module-Level Functions in Other Modules

Suppose there is a cdef function in a Cython file A.pyx that is not a method of a class, but you would like to use it from another Cython module. There are (at least) two options. One option is to make the functions methods of a cdef'd class, then instantiate an object of that type in the other file (this has no weird linking issues). Another is to use ``public extern'' and link in the whole module, which we describe below.

For example, the file A.pyx might contain

cdef int sqr_int(int x):
    return x*x
You would like to call this C-level method directly from a different Cython module. To do so, it is crucial to declare the method public instead:
cdef public int sqr_int(int x):
    return x*x
Then create a file A.pxd that contains
cdef extern int sqr_int(int x)
Finally, to use sqr_int in another Cython module B.pyx, do the following:
cimport sage.rings.A     # this is just an example absolute path
def myfunction():
    print sage.rings.A.sqr_int(5)
Any time you access one Cython module from another one, it's necessary that the compiler know to link in the other Cython module (A.pyx in our example). Tell it to link in A.pyx by including A.pyx in the corresponding entry in setup.py. That entry should look something like this:
    Extension('sage.modular.B', 
              ['sage/modular/B.pyx', 'sage/rings/A.pyx'])
Note: Linking as above means an entire copy of all the code in A.pyx is compiled into the module for B.pyx, so B.so will be larger, and the C-level function you're accessing will not have access to any module-scope variables in A.pyx. This can lead to weird core dumps, depending on the nature of your function.

Cython will generate a file A.pxi that also declares foo. You can ignore that file.

NOTE: Alternatively, you could put include "path/to/A.pxi" in B.pyx and and directly use sqr_int in B.pyx with no scoping:

def myfunction():
    print sqr_int(5)
This is not recommended because it is confusing and unpythonic to not have the scoping information.

See About this document... for information on suggesting changes.