Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Cython C functions from Python

Tags:

python

cython

I have a Cython file called foo.pyx containing the following functions:

def add_one(int n):
    cdef int m = n + 1
    return m

cdef int c_add_one(int n):
    return n + 1

I build this pyx file using cython -a foo.pyx and can then do:

>>> import foo
>>> foo.add_one(5)
6
>>> foo.c_add_one(5)
AttributeError: 'module' object has no attribute 'c_add_one'

So it looks like I can't call c_add_one from python. What are the advantages of declaring a function using cdef?

like image 264
LondonRob Avatar asked Nov 04 '14 15:11

LondonRob


1 Answers

  1. Speed: Cython and C can call cdef and cpdef functions much faster than regular functions. Regular def functions are full-blown Python objects. They require reference counting, the GIL, etc.
  2. Encapsulation: If a function is declared cdef, it will not be exposed to Python users. This is beneficial if the function was never intended for public consumption (e.g. because it doesn't check its parameters, or relates to an implementation detail which might change in the future). Users can still circumvent this via C/Cython, of course, but doing so is more of a hassle than most will bother with. In this way, it's similar to double-underscore name mangling.
like image 125
Kevin Avatar answered Nov 07 '22 05:11

Kevin