Cython Language Overview

#

Overview of the Cython Language

This document informally describes the extensions to the Python language made by Cython. Some day there will be a reference manual covering everything in more detail.

## Contents

- Basics

- Python functions vs. C functions
- Python objects as parameters
- C variable and type definitions
- Automatic type conversions

- Caveats when using a Python string in a C context

- Scope rules
- Statements and expressions

- Differences between C and Cython expressions
- Integer for-loops

- Error return values

- Checking return values of non-Cython functions

- The `include` statement

- Interfacing with External C Code

- External declarations

- Referencing C header files
- Styles of struct/union/enum declaration
- Accessing Python/C API routines
- Resolving naming conflicts - C name specifications

- Public declarations

- Extension Types (Section revised in 0.9)
- Sharing Declarations Between Cython Modules (NEW in 0.8)
- Limitations

- Unsupported Python features
- Semantic differences between Python and Cython

##

Basics

This section describes the basic features of the Cython language. The facilities covered in this section allow you to create Python-callable functions that manipulate C data structures and convert between Python and C data types. Later sections will cover facilities for wrapping external C code, creating new Python types and cooperation between Cython modules.

### Python functions vs. C functions

There are two kinds of function definition in Cython:

Python functions are defined using the def statement, as in Python. They take Python objects as parameters and return Python objects.

C functions are defined using the new cdef statement. They take either Python objects or C values as parameters, and can return either Python objects or C values.

Within a Cython module, Python functions and C functions can call each other freely, but only Python functions can be called from outside the module by interpreted Python code. So, any functions that you want to "export" from your Cython module must be declared as Python functions using def.

Parameters of either type of function can be declared to have C data types, using normal C declaration syntax. For example,

>     def spam(int i, char *s):
>         ...

>     cdef int eggs(unsigned long l, float f):
>         ...

When a parameter of a Python function is declared to have a C data type, it is passed in as a Python object and automatically converted to a C value, if possible. Automatic conversion is currently only possible for numeric types and string types; attempting to use any other type for the parameter of a Python function will result in a compile-time error.

C functions, on the other hand, can have parameters of any type, since they're passed in directly using a normal C function call.

### Python objects as parameters and return values

If no type is specified for a parameter or return value, it is assumed to be a Python object. (Note that this is different from the C convention, where it would default to `int`.) For example, the following defines a C function that takes two Python objects as parameters and returns a Python object:

>     cdef spamobjs(x, y):
>         ...

Reference counting for these objects is performed automatically according to the standard Python/C API rules (i.e. borrowed references are taken as parameters and a new reference is returned).

The name object can also be used to explicitly declare something as a Python object. This can be useful if the name being declared would otherwise be taken as the name of a type, for example,

>     cdef ftang(object int):
>         ...

declares a parameter called `int` which is a Python object. You can also use object as the explicit return type of a function, e.g.

>     cdef object ftang(object int):
>         ...

In the interests of clarity, it is probably a good idea to always be explicit about object parameters in C functions.

### C variable and type definitions

The cdef statement is also used to declare C variables, either local or module-level:

>     cdef int i, j, k
>     cdef float f, g[42], *h

and C struct, union or enum types:

>     cdef struct Grail:
>         int age
>         float volume

>     cdef union Food:
>         char *spam
>         float *eggs

>     cdef enum CheeseType:
>         cheddar, edam,
>         camembert

>     cdef enum CheeseState:
>         hard = 1
>         soft = 2
>         runny = 3

There is currently no special syntax for defining a constant, but you can use an anonymous enum declaration for this purpose, for example,

> `cdef enum:`
> `tons_of_spam = 3`

Note that the words struct, union and enum are used only when defining a type, not when referring to it. For example, to declare a variable pointing to a Grail you would write

>     cdef Grail *gp

and not

>     cdef struct Grail *gp # WRONG

There is also a ctypedef statement for giving names to types, e.g.

>     ctypedef unsigned long ULong

>     ctypedef int *IntPtr

### Automatic type conversions

In most situations, automatic conversions will be performed for the basic numeric and string types when a Python object is used in a context requiring a C value, or vice versa. The following table summarises the conversion possibilities.

C types | From Python types | To Python types
--- | --- | ---
[unsigned] char [unsigned] short int, long | int, long | int
unsigned int unsigned long [unsigned] long long | int, long | long
float, double, long double | int, long, float | float
char * | str | str

#### Caveats when using a Python string in a C context

You need to be careful when using a Python string in a context expecting a char *. In this situation, a pointer to the contents of the Python string is used, which is only valid as long as the Python string exists. So you need to make sure that a reference to the original Python string is held for as long as the C string is needed. If you can't guarantee that the Python string will live long enough, you will need to copy the C string.
Cython detects and prevents some mistakes of this kind. For instance, if you attempt something like

    cdef char *s
    s = pystring1 + pystring2

then Cython will produce the error message "Obtaining char * from temporary Python value". The reason is that concatenating the two Python strings produces a new Python string object that is referenced only by a temporary internal variable that Cython generates. As soon as the statement has finished, the temporary variable will be decrefed and the Python string deallocated, leaving s dangling. Since this code could not possibly work, Cython refuses to compile it.
The solution is to assign the result of the concatenation to a Python variable, and then obtain the char * from that, i.e.

    cdef char *s
    p = pystring1 + pystring2
    s = p

It is then your responsibility to hold the reference p for as long as necessary.
Keep in mind that the rules used to detect such errors are only heuristics. Sometimes Cython will complain unnecessarily, and sometimes it will fail to detect a problem that exists. Ultimately, you need to understand the issue and be careful what you do.

### Scope rules

Cython determines whether a variable belongs to a local scope, the module scope, or the built-in scope completely statically. As with Python, assigning to a variable which is not otherwise declared implicitly declares it to be a Python variable residing in the scope where it is assigned. Unlike Python, however, a name which is referred to but not declared or assigned is assumed to reside in the builtin scope, not the module scope. Names added to the module dictionary at run time will not shadow such names.

You can use a global statement at the module level to explicitly declare a name to be a module-level name when there would otherwise not be any indication of this, for example,

> `global __name__`
> `print __name__`

Without the global statement, the above would print the name of the builtins module.
Note: A consequence of these rules is that the module-level scope behaves the same way as a Python local scope if you refer to a variable before assigning to it. In particular, tricks such as the following will not work in Cython:

>     try:
>       x = True
>     except NameError:
>       True = 1

because, due to the assignment, the True will always be looked up in the module-level scope. You would have to do something like this instead:

>     import __builtin__
>     try:
>       True = __builtin__.True
>     except AttributeError:
>       True = 1

### Statements and expressions

Control structures and expressions follow Python syntax for the most part. When applied to Python objects, they have the same semantics as in Python (unless otherwise noted). Most of the Python operators can also be applied to C values, with the obvious semantics.

If Python objects and C values are mixed in an expression, conversions are performed automatically between Python objects and C numeric or string types.

Reference counts are maintained automatically for all Python objects, and all Python operations are automatically checked for errors, with appropriate action taken.

#### Differences between C and Cython expressions

There are some differences in syntax and semantics between C expressions and Cython expressions, particularly in the area of C constructs which have no direct equivalent in Python.

- An integer literal without an L suffix is treated as a C constant, and will be truncated to whatever size your C compiler thinks appropriate. With an L suffix, it will be converted to Python long integer (even if it would be small enough to fit into a C int).
- There is no `->` operator in Cython. Instead of `p->x`, use `p.x`
- There is no `*` operator in Cython. Instead of `*p`, use `p[0]`
- There is an `&` operator, with the same semantics as in C.
- The null C pointer is called `NULL`, not 0 (and `NULL` is a reserved word).
- Character literals are written with a c prefix, for example:

    c'X'

- Type casts are written `<type>value` , for example:

    cdef char *p, float *q
    p = <char*>q

Warning: Don't attempt to use a typecast to convert between Python and C data types -- it won't do the right thing. Leave Cython to perform the conversion automatically.

#### Integer for-loops

You should be aware that a for-loop such as

> `for i in range(n):`
> `...`

won't be very fast, even if `i` and `n` are declared as C integers, because `range` is a Python function. For iterating over ranges of integers, Cython has another form of for-loop:

> `for i from 0 <= i < n:`
> `...`

If the loop variable and the lower and upper bounds are all C integers, this form of loop will be much faster, because Cython will translate it into pure C code.

Some things to note about the `for-from` loop:

- The target expression must be a variable name.
- The name between the lower and upper bounds must be the same as the target name.
- The direction of iteration is determined by the relations. If they are both from the set {`<`, `<=`} then it is upwards; if they are both from the set {`>`, `>=`} then it is downwards. (Any other combination is disallowed.)

Like other Python looping statements, `break` and `continue` may be used in the body, and the loop may have an `else` clause.

##

### Error return values

If you don't do anything special, a function declared with cdef that does not return a Python object has no way of reporting Python exceptions to its caller. If an exception is detected in such a function, a warning message is printed and the exception is ignored.

If you want a C function that does not return a Python object to be able to propagate exceptions to its caller, you need to declare an exception value for it. Here is an example:

> `cdef int spam() except -1:`
> `...`

With this declaration, whenever an exception occurs inside `spam`, it will immediately return with the value `-1`. Furthermore, whenever a call to `spam` returns `-1`, an exception will be assumed to have occurred and will be propagated.

When you declare an exception value for a function, you should never explicitly return that value. If all possible return values are legal and you can't reserve one entirely for signalling errors, you can use an alternative form of exception value declaration:

> `cdef int spam() except? -1:`
> `...`

The "?" indicates that the value `-1` only indicates a possible error. In this case, Cython generates a call to `PyErr_Occurred`if the exception value is returned, to make sure it really is an error.

There is also a third form of exception value declaration:

> `cdef int spam() except *:`
> `...`

This form causes Cython to generate a call to `PyErr_Occurred` after every call to spam, regardless of what value it returns. If you have a function returning `void` that needs to propagate errors, you will have to use this form, since there isn't any return value to test.

Some things to note:

- Currently, exception values can only declared for functions returning an integer, float or pointer type, and the value must be a literal, not an expression (although it can be negative). The only possible pointer exception value is `NULL`. Void functions can only use the `except *` form.
- The exception value specification is part of the signature of the function. If you're passing a pointer to a function as a parameter or assigning it to a variable, the declared type of the parameter or variable must have the same exception value specification (or lack thereof). Here is an example of a pointer-to-function declaration with an exception value:

    int (*grail)(int, char *) except -1

- You don't need to (and shouldn't) declare exception values for functions which return Python objects. Remember that a function with no declared return type implicitly returns a Python object.

#### Checking return values of non-Cython functions

It's important to understand that the `except` clause does not cause an error to be raised when the specified value is returned. For example, you can't write something like

>     cdef extern FILE *fopen(char *filename, char *mode) except NULL # WRONG!

and expect an exception to be automatically raised if a call to fopen returns NULL. The except clause doesn't work that way; its only purpose is for propagating exceptions that have already been raised, either by a Cython function or a C function that calls Python/C API routines. To get an exception from a non-Python-aware function such as fopen, you will have to check the return value and raise it yourself, for example,

>     cdef FILE *p
>     p = fopen("spam.txt", "r")
>     if p == NULL:
>         raise SpamError("Couldn't open the spam file")

####

#### The `include` statement

For convenience, a large Cython module can be split up into a number of files which are put together using the include statement, for example

>     include "spamstuff.pxi"

The contents of the named file are textually included at that point. The included file can contain any complete top-level Cython statements, including other include statements. The include statement itself can only appear at the top level of a file.

The include statement can also be used in conjunction with public declarations to make C functions and variables defined in one Cython module accessible to another. However, note that some of these uses have been superseded by the facilities described in Sharing Declarations Between Cython Modules, and it is expected that use of the include statement for this purpose will be phased out altogether in future versions.

##

Interfacing with External C Code

One of the main uses of Cython is wrapping existing libraries of C code. This is achieved by using external declarations to declare the C functions and variables from the library that you want to use.

You can also use public declarations to make C functions and variables defined in a Cython module available to external C code. The need for this is expected to be less frequent, but you might want to do it, for example, if you are embedding Python in another application as a scripting language. Just as a Cython module can be used as a bridge to allow Python code to call C code, it can also be used to allow C code to call Python code.

### External declarations

By default, C functions and variables declared at the module level are local to the module (i.e. they have the C static storage class). They can also be declared extern to specify that they are defined elsewhere, for example:

>     cdef extern int spam_counter

>     cdef extern void order_spam(int tons)

#### Referencing C header files

When you use an extern definition on its own as in the examples above, Cython includes a declaration for it in the generated C file. This can cause problems if the declaration doesn't exactly match the declaration that will be seen by other C code. If you're wrapping an existing C library, for example, it's important that the generated C code is compiled with exactly the same declarations as the rest of the library.

To achieve this, you can tell Cython that the declarations are to be found in a C header file, like this:

>     cdef extern from "spam.h":

>         int spam_counter

>         void order_spam(int tons)

The cdef extern from clause does three things:

1. It directs Cython to place a #include statement for the named header file in the generated C code.
2. It prevents Cython from generating any C code for the declarations found in the associated block.
3. It treats all declarations within the block as though they started with cdef extern.

It's important to understand that Cython does not itself read the C header file, so you still need to provide Cython versions of any declarations from it that you use. However, the Cython declarations don't always have to exactly match the C ones, and in some cases they shouldn't or can't. In particular:

1. Don't use const. Cython doesn't know anything about const, so just leave it out. Most of the time this shouldn't cause any problem, although on rare occasions you might have to use a cast. 1
2. Leave out any platform-specific extensions to C declarations such as __declspec().
3. If the header file declares a big struct and you only want to use a few members, you only need to declare the members you're interested in. Leaving the rest out doesn't do any harm, because the C compiler will use the full definition from the header file.
   In some cases, you might not need any of the struct's members, in which case you can just put `pass` in the body of the struct declaration, e.g.
   `cdef extern from "foo.h":
   struct spam:
   pass`
   Note that you can only do this inside a cdef extern from block; struct declarations anywhere else must be non-empty.
4. If the header file uses typedef names such as size_t to refer to platform-dependent flavours of numeric types, you will need a corresponding ctypedef statement, but you don't need to match the type exactly, just use something of the right general kind (int, float, etc). For example,

    ctypedef int size_t

will work okay whatever the actual size of a size_t is (provided the header file defines it correctly).
5. If the header file uses macros to define constants, translate them into a dummy enum declaration.
6. If the header file defines a function using a macro, declare it as though it were an ordinary function, with appropriate argument and result types.

A few more tricks and tips:

- If you want to include a C header because it's needed by another header, but don't want to use any declarations from it, put `pass` in the extern-from block:

`cdef extern from "spam.h":`
`pass`

- If you want to include some external declarations, but don't want to specify a header file (because it's included by some other header that you've already included) you can put `*` in place of the header file name:

> > `cdef extern from *:`
> > `...`

#### Styles of struct, union and enum declaration

There are two main ways that structs, unions and enums can be declared in C header files: using a tag name, or using a typedef. There are also some variations based on various combinations of these.

It's important to make the Cython declarations match the style used in the header file, so that Cython can emit the right sort of references to the type in the code it generates. To make this possible, Cython provides two different syntaxes for declaring a struct, union or enum type. The style introduced above corresponds to the use of a tag name. To get the other style, you prefix the declaration with ctypedef, as illustrated below.

The following table shows the various possible styles that can be found in a header file, and the corresponding Cython declaration that you should put in the cdef exern from block. Struct declarations are used as an example; the same applies equally to union and enum declarations.

Note that in all the cases below, you refer to the type in Cython code simply as `Foo`, not `struct Foo`.

| C code | Possibilities for corresponding Cython code | Comments
1 | `struct Foo {` `...` `};` | `cdef struct Foo:` `...` | Cython will refer to the type as `struct Foo` in the generated C code`.`
2 | `typedef struct {` `...` `} Foo;` | `ctypedef struct Foo:` `...` | Cython will refer to the type simply as `Foo` in the generated C code.
3 | `typedef struct foo {` `...` `} Foo;` | `cdef struct foo:` `...` `ctypedef foo Foo #optional` | If the C header uses both a tag and a typedef with different names, you can use either form of declaration in Cython (although if you need to forward reference the type, you'll have to use the first form).
`ctypedef struct Foo:` `...`
4 | `typedef struct Foo {` `...` `} Foo;` | `cdef struct Foo:` `...` | If the header uses the same name for the tag and the typedef, you won't be able to include a ctypedef for it -- but then, it's not necessary.

#### Accessing Python/C API routines

One particular use of the cdef extern from statement is for gaining access to routines in the Python/C API. For example,

>     cdef extern from "Python.h":

>         object PyString_FromStringAndSize(char *s, int len)

will allow you to create Python strings containing null bytes.

### Resolving naming conflicts - C name specifications

Each Cython module has a single module-level namespace for both Python and C names. This can be inconvenient if you want to wrap some external C functions and provide the Python user with Python functions of the same names.

Cython 0.8 provides a couple of different ways of solving this problem. The best way, especially if you have many C functions to wrap, is probably to put the extern C function declarations into a different namespace using the facilities described in the section on sharing declarations between Cython modules.

The other way is to use a c name specification to give different Cython and C names to the C function. Suppose, for example, that you want to wrap an external function called `eject_tomato`. If you declare it as

>     cdef extern void c_eject_tomato "eject_tomato" (float speed)

then its name inside the Cython module will be `c_eject_tomato`, whereas its name in C will be `eject_tomato`. You can then wrap it with

>     def eject_tomato(speed):
>       c_eject_tomato(speed)

so that users of your module can refer to it as `eject_tomato`.

Another use for this feature is referring to external names that happen to be Cython keywords. For example, if you want to call an external function called `print`, you can rename it to something else in your Cython module.

As well as functions, C names can be specified for variables, structs, unions, enums, struct and union members, and enum values. For example,

>     cdef extern int one "ein", two "zwei"
>     cdef extern float three "drei"

>     cdef struct spam "SPAM":
>       int i "eye"

> `cdef enum surprise "inquisition":`
> `first "alpha"`
> `second "beta" = 3`

### Public Declarations

You can make C variables and functions defined in a Cython module accessible to external C code (or another Cython module) using the `public` keyword, as follows:

> `cdef public int spam # public variable declaration`

> `cdef public void grail(int num_nuns): # public function declaration`
> `...`

If there are any `public` declarations in a Cython module, a .h file is generated containing equivalent C declarations for inclusion in other C code.

Cython also generates a .pxi file containing Cython versions of the declarations for inclusion in another Cython module using the include statement. If you use this, you will need to arrange for the module using the declarations to be linked against the module defining them, and for both modules to be available to the dynamic linker at run time. I haven't tested this, so I can't say how well it will work on the various platforms.

> NOTE: If all you want to export is an extension type, there is now a better way -- see Sharing Declarations Between Cython Modules.

##

Extension Types

One of the most powerful features of Cython is the ability to easily create new built-in Python types, called extension types. This is a major topic in itself, so there is a separate page devoted to it.

##

Sharing Declarations Between Cython Modules

Cython 0.8 introduces a substantial new set of facilities allowing a Cython module to easily import and use C declarations and extension types from another Cython module. You can now create a set of co-operating Cython modules just as easily as you can create a set of co-operating Python modules. There is a separate page devoted to this topic.

##

Limitations

### Unsupported Python features

Cython is not quite a full superset of Python. The following restrictions apply:

> - Function definitions (whether using def or cdef) cannot be nested within other function definitions.
> - Class definitions can only appear at the top level of a module, not inside a function.
> - The`import *` form of import is not allowed anywhere (other forms of the import statement are fine, though).
> - Generators cannot be defined in Cython.
> - The `globals()` and `locals()` functions cannot be used.

The above restrictions will most likely remain, since removing them would be difficult and they're not really needed for Cython's intended applications.

There are also some temporary limitations, which may eventually be lifted, including:

> - Class and function definitions cannot be placed inside control structures.
> - In-place arithmetic operators (+=, etc) are not yet supported.
> - List comprehensions are not yet supported.
> - There is no support for Unicode.
> - Special methods of extension types cannot have functioning docstrings.
> - The use of string literals as comments is not recommended at present, because Cython doesn't optimize them away, and won't even accept them in places where executable statements are not allowed.

### Semantic differences between Python and Cython

#### Behaviour of class scopes

In Python, referring to a method of a class inside the class definition, i.e. while the class is being defined, yields a plain function object, but in Cython it yields an unbound method2. A consequence of this is that the usual idiom for using the classmethod and staticmethod functions, e.g.

>     class Spam:

>       def method(cls):
>         ...

>       method = classmethod(method)

will not work in Cython. This can be worked around by defining the function outside the class, and then assigning the result of classmethod or staticmethod inside the class, i.e.

>     def Spam_method(cls):
>       ...

>     class Spam:

>       method = classmethod(Spam_method)

#

Footnotes

1. A problem with const could arise if you have something like

>     cdef extern from "grail.h":
>       char *nun

where grail.h actually contains

>     extern const char *nun;

and you do

>     cdef void languissement(char *s):
>       #something that doesn't change s

>     ...

>     languissement(nun)

which will cause the C compiler to complain. You can work around it by casting away the constness:

>     languissement(<char *>nun)

2. The reason for the different behaviour of class scopes is that Cython-defined Python functions are PyCFunction objects, not PyFunction objects, and are not recognised by the machinery that creates a bound or unbound method when a function is extracted from a class. To get around this, Cython wraps each method in an unbound method object itself before storing it in the class's dictionary.