This tutorial will show you how to use Cython (
.pyx) in Python. Cython is a superset of Python that compiles to C. Cython modules can be used to speed up some parts of your project as C is a very fast language.
A Cython module must be compiled before it can be used and this compilation happens in two stages. A Cyton module (
hello.pyx) is first compiled to a C-file (
.c file is then compiled to a
.pyd file (Windows). I am going to compile Cython code from the command-prompt by using a setup file (
setup.py) in this tutorial. You will need the following libraries: numpy, Cython and setuptools. Remember that names is case sensitive in Python.
I have created two simple Cython modules:
date_and_time.pyx. These files is stored under annytab/cython in my project. The contents of these files is shown below.
# File: annytab/cython/hello.pyx # Say hello to someone def say_hello_to(name): print("Hello %s!" % name)
# File: annytab/cython/date_and_time.pyx # Import libraries cimport cpython.datetime # Get today's date and time def now(): print("Today's date and time: %s" % cpython.datetime.datetime.now())
A setup file (
setup.py) is used to compile my two Cython modules, the setup file is stored in the same folder as the
.pyx files. The contents of the file is shown below.
# Import libraries import numpy import setuptools import Cython.Build # Compile Cython files setuptools.setup(name = 'Hello', ext_modules = Cython.Build.cythonize('hello.pyx'), include_dirs=[numpy.get_include()]) setuptools.setup(name = 'Date and Time', ext_modules = Cython.Build.cythonize('date_and_time.pyx'), include_dirs=[numpy.get_include()])
Open the command prompt, search for
cmd if you can’t find it. Browse to the folder where your
setup.py file is located and type
python setup.py build_ext --inplace. You must have added a path to Python in environment variables for this to work, read Install Python and libraries with Visual Studio if you need help with this.
Microsoft Windows [Version 10.0.18363.476] (c) 2019 Microsoft Corporation. Med ensamrätt. C:\WINDOWS\system32>cd C:\DATA\Python-projects\Iris\Iris\annytab\cython C:\DATA\Python-projects\Iris\Iris\annytab\cython>python setup.py build_ext --inplace
The compilation process saved files to the directory where the setup file is located. Now I am able to call methods in my Cython modules from Python modules.
# Import libraries import annytab.cython.hello import annytab.cython.date_and_time # Say hello annytab.cython.hello.say_hello_to('Wayne Gretzky') # Get today's date and time annytab.cython.date_and_time.now()