Search code examples
pythondeclarationcython

Definition of def, cdef and cpdef in Cython


What is the difference between def, cdef and cpdef when I declare a function?

The difference between def and the others is more or less clear. And I've also seen that sometimes it's added the return type in the declaration (cdef void/double/int... name) and sometimes not.

How can I declare a string variable in Cython, as I didn't know it? I declared it as object.


Solution

  • def declares a function in Python. Since Cython is based on C runtime, it allows you to use cdef and cpdef.

    cdef declares function in the layer of C language. As you know (or not?) in C language you have to define type of returning value for each function. Sometimes function returns with void, and this is equal for just return in Python.

    Python is an object-oriented language. So you also can define class method in layer of C++ language, and override this methods in subclasses:

    cdef class A:
        cdef foo(self):
            print "A"
    
    cdef class B(A)
        cdef foo(self, x=None)
            print "B", x
    
    cdef class C(B):
        cpdef foo(self, x=True, int k=3)
            print "C", x, k
    

    Summary, why do we need to use def, cdef and cpdef? Because if you use Cython, your Python code will be converted into C code before compile. So with this things you can control the resulting C-code listing.

    For more information I suggest you to read the official documentation: http://docs.cython.org/src/reference/language_basics.html