Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Getting started using Cython

Using Cython consists of these steps:
1. Write a .pyx source file 1. Run the Cython compiler to generate a C file 1. Run a C compiler to generate a compiled library 1. Run the Python interpreter and ask it to import the module
However there are several options to automate these steps:
1. The SAGE mathematics software system provides excellent support for using Cython and NumPy from an interactive command line (like IPython) or through a notebook interface (like Maple/Mathematica). See this documentation. 1. A version of pyximport is shipped with Cython, so that you can import pyx-files dynamically into Python and have them compiled automatically. 1. Cython supports distutils so that you can very easily create build scripts which automate the process, this is the preferred method for full programs. (TODO: Write a section here.) 1. Manual compilation (see below)

Note: If using another interactive command line environment than SAGE, like IPython or Python itself, it is important that you restart the process when you recompile the module. It is not enough to issue an "import" statement again.

Installation of Cython

Unless you are used to some other automatic method: download Cython (0.9.8.1.1 or later), unpack it, and run the usual python setup.py install. This will install a cython executable on your system. It is also possible to use Cython from the source directory without installing (simply launch cython.py in the root directory).

As of this writing SAGE comes with an older release of Cython. So if using SAGE you should download the newest Cython and then execute

$ cd path/to/cython-distro
$ path-to-sage/sage -python setup.py install

This will install the newest Cython into SAGE.

Manual compilation

As it is always important to know what is going on, I'll describe the manual method here. First Cython is run:

$ cython yourmod.pyx

This creates yourmod.c which is the C source for a Python extension module. A useful additional switch is -a which will generate a document (yourmod.html) that shows which Cython code translates to which C code line by line.

Then we compile the C file. This may vary according to your system, but the C file should be built like Python was built. Python documentation for writing extensions should have some details. On Linux this often means something like

$ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.5 -o yourmod.so yourmod.c

gcc should have access to the NumPy C header files so if they are not installed at /usr/include/numpy or similar you may need to pass another option for those.

This creates yourmod.so in the same directory, which is importable by Python by using a normal import yourmod statement.

Something went wrong with that request. Please try again.