How to import and use Cython in Python

AI Maverick
2 min readMar 17, 2022

--

In this review, I talk about the useful tips to use the *.pyx Cython files in the python package. You can find the related links to install and compile the Cython as well.

Cython is just like Python, with the main difference being that it refers to C references. The reason that we use Cython is to increase the compilation speed as the C language is faster than Python. This tutorial assumes that you are working with the Windows OS.

Compile the Cython

To use the Cython file, you first need to compile it through the Cython command, and it will create a c file and then uses the c file. Therefore, you need to install the Cython first.

pip install Cython
pip install --upgrade cython

After installing the Cython, you can start to write the Cython program in a pyx file. Then it is time to compile the Cython file via the terminal.

Cython helloWorld.pyx

The best way to compile the Cython program is to run the setup.py file, which is in the exact directory as the Cython and Python files. Imagine that you have the following Cython file, called the test.pyx.

Complete documentation to build a setup file for the Cython.

cimport cythonimport numpy as npcimport numpy as npcdef void method():
print(np.ndarray)

Therefore, the setup.py would be

import setuptoolsimport Cython.Build as cbsetuptools.setup(name='My Cython Project',     ext_modules=cb.cythonize('test.pyx'))

Open the terminal in the same directory you have the Cython file and compile your setup.py.

python setup.py

After compiling the Cython, you can import it into the Python project.

--

--

No responses yet