Cython for Pythonistas Part 1
An article brought to you about Cython minus all the unreadable documentation.For a beginner, the biggest challenge in building software is to be able to understand the software’s documentation. With lack of reliable medium posts and spoon feeding , beginners tend to feel demotivated towards active learning. This post teaches the know-how of Cython without delving into a documentation-styled tutorial.
The above snippet is something that I have been doing recently.This is called cython code. Remember C/C++? , where we perform ‘static typing’ which means adding static type declarations at a loss of readability. You can do that in Python as well with the help of Cython.
What is Cython?
Cython is a Python compiler.This means that it can compile normal Python code without changes (with a few obvious exceptions of some as-yet unsupported language features, see Cython limitations). However, for performance critical code, it is often helpful to add static type declarations, as they will allow Cython to step out of the dynamic nature of the Python code and generate simpler and faster C code — sometimes faster by orders of magnitude.
Some takeaways and FAQs from this snippet:
- What is cimport?
cimport is a special import statement. When a module wants to use something declared in another module’s definition file, it imports it using the cimport
statement.
2. There are two parts of a Cython module.What you see above is a .pyx file .A definition file with a .pxd
suffix, containing C declarations that are to be available to other Cython modules, and an implementation file with a .pyx
suffix, containing everything else.
3. C styled functions are initialized with cdef or cpdef. Here is the difference.
cdef
is used for Cython functions that are intended to be pure ‘C’ functions. All types must be declared.
cpdef
functions combine both def
and cdef
by creating two functions; a cdef
for C types and a def
fr Python types. This exploits early binding so that cpdef
functions may be as fast as possible when using C fundamental types (by using cdef
). cpdef
functions use dynamic binding when passed Python objects and this might much slower, perhaps as slow as def
declared functions.
In the next part, we shall talk about Setup file and the internal workings of PyObject in C API. Feel free to ask questions in the comments below.
Follow me on LinkedIn, Github.
Thank You!