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
?
cdef
and cpdef
functions much faster than regular functions. Regular def
functions are full-blown Python objects. They require reference counting, the GIL, etc.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With