Differences between Cython and Pyrex

Warning

Both Cython and Pyrex are moving targets. It has come to the pointthat an explicit list of all the differences between the twoprojects would be laborious to list and track, but hopefullythis high-level list gives an idea of the differences thatare present. It should be noted that both projects make an effortat mutual compatibility, but Cython’s goal is to be as close toand complete as Python as reasonable.

Python 3 Support

Cython creates .c files that can be built and used with bothPython 2.x and Python 3.x. In fact, compiling your module withCython may very well be an easy way to port code to Python 3.

Cython also supports various syntax additions that came withPython 3.0 and later major Python releases. If they do not conflictwith existing Python 2.x syntax or semantics, they are usually justaccepted by the compiler. Everything else depends on thecompiler directive language_level=3(see compiler directives).

List/Set/Dict Comprehensions

Cython supports the different comprehensions defined by Python 3 forlists, sets and dicts:

  1. [expr(x) for x in A] # list
  2. {expr(x) for x in A} # set
  3. {key(x) : value(x) for x in A} # dict

Looping is optimized if A is a list, tuple or dict. You can usethe forfrom syntax, too, but it isgenerally preferred to use the usual forinrange(…) syntax with a C run variable (e.g. cdef int i).

Note

see Automatic range conversion

Note that Cython also supports set literals starting from Python 2.4.

Keyword-only arguments

Python functions can have keyword-only arguments listed after the parameter and before the * parameter if any, e.g.:

  1. def f(a, b, *args, c, d = 42, e, **kwds):
  2. ...

Here c, d and e cannot be passed as position arguments and must bepassed as keyword arguments. Furthermore, c and e are required keywordarguments, since they do not have a default value.

If the parameter name after the * is omitted, the function will not accept anyextra positional arguments, e.g.:

  1. def g(a, b, *, c, d):
  2. ...

takes exactly two positional parameters and has two required keyword parameters.

Conditional expressions “x if b else y”

Conditional expressions as described inhttps://www.python.org/dev/peps/pep-0308/:

  1. X if C else Y

Only one of X and Y is evaluated (depending on the value of C).

cdef inline

Module level functions can now be declared inline, with the inlinekeyword passed on to the C compiler. These can be as fast as macros.:

  1. cdef inline int something_fast(int a, int b):
  2. return a*a + b

Note that class-level cdef functions are handled via a virtualfunction table, so the compiler won’t be able to inline them in almost allcases.

Assignment on declaration (e.g. “cdef int spam = 5”)

In Pyrex, one must write:

  1. cdef int i, j, k
  2. i = 2
  3. j = 5
  4. k = 7

Now, with cython, one can write:

  1. cdef int i = 2, j = 5, k = 7

The expression on the right hand side can be arbitrarily complicated, e.g.:

  1. cdef int n = python_call(foo(x,y), a + b + c) - 32

‘by’ expression in for loop (e.g. “for i from 0 <= i < 10 by 2”)

  1. for i from 0 <= i < 10 by 2:
  2. print i

yields:

  1. 0
  2. 2
  3. 4
  4. 6
  5. 8

Note

Usage of this syntax is discouraged as it is redundant with thenormal Python for loop.See Automatic range conversion.

Boolean int type (e.g. it acts like a c int, but coerces to/from python as a boolean)

In C, ints are used for truth values. In python, any object can be used as atruth value (using the nonzero() method), but the canonical choicesare the two boolean objects True and False. The bint (for“boolean int”) type is compiled to a C int, but coerces to and fromPython as booleans. The return type of comparisons and several builtins is abint as well. This reduces the need for wrapping things inbool(). For example, one can write:

  1. def is_equal(x):
  2. return x == y

which would return 1 or 0 in Pyrex, but returns True or False inCython. One can declare variables and return values for functions to be of thebint type. For example:

  1. cdef int i = x
  2. cdef bint b = x

The first conversion would happen via x.int() whereas the second wouldhappen via x.bool() (a.k.a. nonzero()), with appropriateoptimisations for known builtin types.

Executable class bodies

Including a working classmethod():

  1. cdef class Blah:
  2. def some_method(self):
  3. print self
  4. some_method = classmethod(some_method)
  5. a = 2*3
  6. print "hi", a

cpdef functions

Cython adds a third function type on top of the usual def andcdef. If a function is declared cpdef it can be calledfrom and overridden by both extension and normal python subclasses. You canessentially think of a cpdef method as a cdef method +some extras. (That’s how it’s implemented at least.) First, it creates adef method that does nothing but call the underlyingcdef method (and does argument unpacking/coercion if needed). Atthe top of the cdef method a little bit of code is added to seeif it’s overridden, similar to the following pseudocode:

  1. if hasattr(type(self), '__dict__'):
  2. foo = self.foo
  3. if foo is not wrapper_foo:
  4. return foo(args)
  5. [cdef method body]

To detect whether or not a type has a dictionary, it just checks thetp_dictoffset slot, which is NULL (by default) for extension types,but non- null for instance classes. If the dictionary exists, it does a singleattribute lookup and can tell (by comparing pointers) whether or not thereturned result is actually a new function. If, and only if, it is a newfunction, then the arguments packed into a tuple and the method called. Thisis all very fast. A flag is set so this lookup does not occur if one calls themethod on the class directly, e.g.:

  1. cdef class A:
  2. cpdef foo(self):
  3. pass
  4.  
  5. x = A()
  6. x.foo() # will check to see if overridden
  7. A.foo(x) # will call A's implementation whether overridden or not

See Early Binding for Speed for explanation and usage tips.

Automatic range conversion

This will convert statements of the form for i in range(…) to for i
from …
when i is any cdef’d integer type, and the direction (i.e. signof step) can be determined.

Warning

This may change the semantics if the range causesassignment to i to overflow. Specifically, if this option is set, an errorwill be raised before the loop is entered, whereas without this option the loopwill execute until a overflowing value is encountered. If this affects you,change Cython/Compiler/Options.py (eventually there will be a betterway to set this).

More friendly type casting

In Pyrex, if one types <int>x where x is a Python object, one will getthe memory address of x. Likewise, if one types <object>i where iis a C int, one will get an “object” at location i in memory. This leadsto confusing results and segfaults.

In Cython <type>x will try and do a coercion (as would happen on assignment ofx to a variable of type type) if exactly one of the types is a python object.It does not stop one from casting where there is no conversion (though it willemit a warning). If one really wants the address, cast to a void * first.

As in Pyrex <MyExtensionType>x will cast x to type MyExtensionTypewithout any type checking. Cython supports the syntax <MyExtensionType?> to dothe cast with type checking (i.e. it will throw an error if x is not a(subclass of) MyExtensionType.

Optional arguments in cdef/cpdef functions

Cython now supports optional arguments for cdef andcpdef functions.

The syntax in the .pyx file remains as in Python, but one declares suchfunctions in the .pxd file by writing cdef foo(x=*). The number ofarguments may increase on subclassing, but the argument types and order mustremain the same. There is a slight performance penalty in some cases when acdef/cpdef function without any optional is overridden with one that does havedefault argument values.

For example, one can have the .pxd file:

  1. cdef class A:
  2. cdef foo(self)
  3.  
  4. cdef class B(A):
  5. cdef foo(self, x=*)
  6.  
  7. cdef class C(B):
  8. cpdef foo(self, x=*, int k=*)

with corresponding .pyx file:

  1. from __future__ import print_function
  2.  
  3. cdef class A:
  4. cdef foo(self):
  5. print("A")
  6.  
  7. cdef class B(A):
  8. cdef foo(self, x=None):
  9. print("B", x)
  10.  
  11. cdef class C(B):
  12. cpdef foo(self, x=True, int k=3):
  13. print("C", x, k)

Note

this also demonstrates how cpdef functions can overridecdef functions.

Function pointers in structs

Functions declared in struct are automatically converted tofunction pointers for convenience.

C++ Exception handling

cdef functions can now be declared as:

  1. cdef int foo(...) except +
  2. cdef int foo(...) except +TypeError
  3. cdef int foo(...) except +python_error_raising_function

in which case a Python exception will be raised when a C++ error is caught.See Using C++ in Cython for more details.

Synonyms

cdef import from means the same thing as cdef extern from

Source code encoding

Cython supports PEP 3120 and PEP 263, i.e. you can start your Cython sourcefile with an encoding comment and generally write your source code in UTF-8.This impacts the encoding of byte strings and the conversion of unicode stringliterals like u'abcd' to unicode objects.

Automatic typecheck

Rather than introducing a new keyword typecheck as explained in thePyrex docs,Cython emits a (non-spoofable and faster) typecheck wheneverisinstance() is used with an extension type as the second parameter.

From future directives

Cython supports several from future import … directives, namelyabsolute_import, unicode_literals, print_function and division.

With statements are always enabled.

Pure Python mode

Cython has support for compiling .py files, andaccepting type annotations using decorators and othervalid Python syntax. This allows the same source tobe interpreted as straight Python, or compiled foroptimized results. See Pure Python Mode for more details.