Python Programming/Cython

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Cython (not to be confused with CPython) is a compiler of Python-like source code to the C language, from which it is compiled by a C compiler to binary executable. The objective is a significant speedup compared to interpreting the Python code in CPython, the standard interpreter. Cython is usually used to create extension modules for Python. The source code language compilable by Cython is a near superset of Python.

You can install Cython using pip install Cython. However, in order for Cython to work, you will need a working C compiler. On Linux, you usually have one; on Windows, you can install and use Microsoft Visual C++ compiler or MinGW.

Beyond the normal Python, Cython-compilable Python source can contain C-like declarations of variable types, leading to speedups of the compiled code.

Cython-compilable Python source code files conventionally use extension pyx.

The compiled extension module still needs CPython (the normal Python interpreter) to run, and can call other Python modules, including pure Python modules. This is because, where required, Cython compiles to C code that uses the CPython API to achieve general Python-like behavior.

External links[edit]