Cython

This is an old revision of this page, as edited by Addbot (talk | contribs) at 16:51, 27 February 2013 (Bot: Migrating 5 interwiki links, now provided by Wikidata on d:q975594 (Report Errors)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Not to be confused with CPython.

The Cython programming language is a superset of Python with a foreign function interface for invoking C/C++ routines and the ability to declare the static type of routine parameters, local variables, subroutine results, and class attributes.[4]

Developer(s)Robert Bradshaw, Stefan Behnel, et al.
Initial releaseError: df must be either "yes" or "y" (help)[1]
Stable release3.1.3[2] Edit this on Wikidata (13 August 2025; 16 days ago (13 August 2025)) [±]
Preview release3.0.0 beta 2 (27 March 2023; 2 years ago (2023-03-27)[3]) [±]
Repository
Operating systemCross-platform
TypeProgramming language
LicenseApache License
Websitecython.org

Overview

Cython is a compiled language that generates CPython extension modules. These extension modules can then be loaded and used by regular Python code using the import statement. Cython is written in Python and works on Windows, Linux, and Mac OS X, producing source files compatible with Python 2.4 through 3.3.

Hello World

 
Hello World in Cython

Cython has an unusually involved hello world program because it interfaces with the Python C API and the distutils extension building facility. At least three files are required for a basic project:

  • A setup.py file to invoke the distutils build process that generates the extension module
  • A main python program to load the extension module
  • Cython source file(s)

The following code listings demonstrate the build and launch process.

# hello.pyx
def say_hello():
	print "Hello World!"
# launch.py 
import hello
hello.say_hello()
# setup.py 
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("hello", ["hello.pyx"])]

setup(
  name = 'Hello world app',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)

These commands build and launch the program

$ python setup.py build_ext --inplace
$ python launch.py

History

Cython is a derivative of the Pyrex language, and supports more features and optimizations than Pyrex.[5][6]

Cython was forked from Pyrex in 2007 by developers of the Sage computer algebra package, because they were unhappy with Pyrex's limitations and could not get patches accepted by Pyrex's maintainer Greg Ewing, who envisioned a much smaller scope for his tool than the Sage developers had in mind. They then forked Pyrex as SageX. When they found people were downloading Sage just to get SageX, and developers of other packages (including Stefan Behnel, who maintains LXML) were also maintaining forks of Pyrex, SageX was split off the Sage project and merged with cython-lxml to become Cython.[7]

Example

Cython files have a .pyx extension. At its most basic, Cython code looks exactly like Python code. However, whereas standard Python is dynamically typed, in Cython, types can optionally be provided, allowing for improved performance, allowing loops to be converted into C loops where possible. For example:

def primes(int kmax): # The argument will be converted to int or raise a TypeError
    cdef int n, k, i # These variables are declared with C types.
    cdef int p[1000] # Another C type.
    result = [] # A Python type.
    if kmax > 1000:
        kmax = 1000
    k = 0
    n = 2
    while k < kmax:
        i = 0
        while i < k and n % p[i] != 0:
            i = i + 1
        if i == k:
            p[k] = n
            k = k + 1
            result.append(n)
        n = n + 1
    return result

Static type declarations and Performance

A Cython program that implements the same algorithm as a corresponding Python program may consume fewer computing resources such as core memory and processing cycles due to differences between the CPython and Cython execution models. On the one hand, a basic Python program is loaded and executed by the CPython virtual machine, so both the runtime and the program itself consume computing resources. On the other hand, a Cython program is compiled to C code, which is further compiled to machine code, so the virtual machine is used only briefly when the program is loaded.[8][9][10][11]

Cython employs

  • Optimistic optimizations
  • Type inference
  • Low overhead in control structures
  • Low function call overhead[12][13]

Since C is the intermediate language, performance will depend on the C compiler.

Uses

Cython is particularly popular among scientific users of Python,[10][14][15] where it has "the perfect audience" according to Python developer Guido van Rossum.[16] Of particular note:

  • The free software Sage computer algebra system depends on Cython, both for performance and to interface with other libraries.[17]
  • Significant parts of the scientific and numerical computing libraries SciPy and NumPy are written in Cython.[18][19]

Cython's ___domain is not limited to just numerical computing. For example, the lxml XML toolkit is written mostly in Cython, and Cython is used to provide Pythonic bindings for many C and C++ libraries ranging from the graphics library OpenGL[20] to the messaging library ZeroMQ.[21]

References

  1. ^ 28th July 2007: official Cython launch, The Cython Compiler for C-Extensions in Python, Dr. Stefan Behnel, EuroPython 2008, Vilnius/Lietuva
  2. ^ "Release 3.1.3". 13 August 2025. Retrieved 14 August 2025.
  3. ^ Cython Changelog, cython, 2023-05-15, retrieved 2023-05-19
  4. ^ http://docs.cython.org/src/quickstart/overview.html
  5. ^ Differences between Cython and Pyrex
  6. ^ Greg Ewing, Re: VM and Language summit info for those not at Pycon (and those that are!). Message to the electronic mailing-list python-dev, 21 March 2011. Retrieved 5 May 2011.
  7. ^ Says Sage and Cython developer Robert Bradshaw at the Sage Days 29 conference. Cython: Past, Present and Future, youtube.com, 22 March 2011. Retrieved 5 May 2011.
  8. ^ http://technicaldiscovery.blogspot.com/2011/06/speeding-up-python-numpy-cython-and.html
  9. ^ Stefan Behnel, Robert Bradshaw, Craig Citro, Lisandro Dalcin, Dag Sverre Seljebotn, Kurt Smith (2011). "Cython: The Best of Both Worlds". Computing in Science and Engineering. 13 (2): 31–39. doi:10.1109/MCSE.2010.118.{{cite journal}}: CS1 maint: multiple names: authors list (link)
  10. ^ a b Dag Sverre Seljebot (2009). "Fast numerical computations with Cython". Proceedings of the 8 th Python in Science Conference (SciPy 2009): 15–22. {{cite journal}}: line feed character in |journal= at position 21 (help)
  11. ^ I. Wilbers; H. P. Langtangen; Å. Ødegård (2009). B. Skallerud; H. I. Andersson (ed.). "Using Cython to Speed up Numerical Python Programs" (pdf). Proceedings of MekIT'09: 495–512. Retrieved June 14, 2011.{{cite journal}}: CS1 maint: multiple names: authors list (link)
  12. ^ wrapper benchmarks for several Python wrapper generators (except Cython)
  13. ^ wrapper benchmarks for Cython, Boost.Python and PyBindGen
  14. ^ inSCIght: The Scientific Computing Podcast, Episode 6
  15. ^ Jarrod Millman and Michael Aivazis (2011). "Python for Scientists and Engineers". Computing in Science and Engineering. 13 (2): 9–12. doi:10.1109/MCSE.2011.36.
  16. ^ Who also criticizes Cython: Re: VM and Language summit info for those not at Pycon (and those that are!). Message to the electronic mailing-list python-dev, 21 March 2011. Retrieved 5 May 2011.
  17. ^ Burcin Erocal and William Stein (2010). "The Sage Project: Unifying Free Mathematical Software to Create a Viable Alternative to Magma, Maple, Mathematica and MATLAB" (PDF). Mathematical Software‚ ICMS 2010. 6327. Springer Berlin / Heidelberg: 12–27. doi:10.1007/978-3-642-15582-6_4.
  18. ^ SciPy 0.7.2 release notes
  19. ^ NumPy ticket talking about moving from Pyrex to Cython
  20. ^ PyOpenGL: The Python OpenGL Binding
  21. ^ http://www.zeromq.org/bindings:python