Compiling Cython extensions
The Cython syntax is, by design, a superset of Python. Cython can compile, with a few exceptions, most Python modules without requiring any change. Cython source files have the .pyx
extension and can be compiled to produce a C file using the cython
command.
All that is required to convert Python code to Cython is some syntactic modifications that we will see throughout this chapter (such as when declaring variables and functions) as well as compilation. While this procedure may seem intimidating at first, Cython will more than make up for itself via the computational benefits that it offers.
First off, to install Cython, we can simply run the pip
command, like this:
$pip install cython
Refer to the documentation at https://pypi.org/project/Cython/ for more details. Our first Cython script will contain a simple function that prints Hello, World!
as the output. Follow these next steps:
- Create a new
hello.pyx
file containing the following...