4.1 Cython

Cython is a compiled version of Python; it is based on Pyrex (http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/). To a large degree, Cython has changed based on what Sage's developers needed: Cython has been developed in concert with Sage. However, it is an independent project now which is used beyond the scope of Sage.

As such, it is a young, but developing, language, with young, but developing, documentation. See its web page, http://www.cython.org/, for the most up-to-date information.

Python is an interpreted language and has no declared data types for variables. These features make it easy to write and debug, but Python code can sometimes be slow. Cython code can look a lot like Python, but it gets translated into C code (often very efficient C code) and then compiled. Thus it offers a language which is familiar to Python developers, but with the potential for much greater speed.

There are several ways to create and build Cython code in Sage.

  1. In the Sage Notebook begin any cell with %cython. When you evaluate that cell,
    1. It is saved to a file.
    2. Cython is run on it with all the standard Sage libraries automatically linked if necessary.
    3. The resulting .so file is then loaded into your running instance of Sage.
    4. The functionality defined in that cell is now available for you to use in the notebook. Also, the output cell has a link to the C program that was compiled to create the .so file.

  2. Create an .spyx file and attach or load it from the command line. This is similar to creating a %cython cell in the notebook but works completely from the command line (and not from the notebook).

  3. Create a .pyx file in the Sage library and add a listing for it to the variable ext_modules in the file SAGE_ROOT/devel/sage/setup.py. For example, the file SAGE_ROOT/devel/sage/sage/graphs/chrompoly.pyx has lines
        Extension('sage.graphs.chrompoly',
                  ['sage/graphs/chrompoly.pyx']
                  ), \
    
    in setup.py. Also, the module - in this example sage.graphs.ch rompoly - needs to be added to the packages list in setup.py . Then type sage -b to build Sage with the new code.



Subsections
See About this document... for information on suggesting changes.