IPython Documentation

Table Of Contents

Previous topic

autoreload

Next topic

octavemagic

This Page

cythonmagic

Magic command interface for interactive work with Cython

Note

The Cython package needs to be installed separately. It can be obtained using easy_install or pip.

Usage

To enable the magics below, execute %load_ext cythonmagic.

%%cython

%cython [-c COMPILE_ARGS] [--link-args LINK_ARGS] [-l LIB] [-n NAME]
            [-L dir] [-I INCLUDE] [-+] [-f] [-a]

Compile and import everything from a Cython code cell.

The contents of the cell are written to a .pyx file in the directory IPYTHONDIR/cython using a filename with the hash of the code. This file is then cythonized and compiled. The resulting module is imported and all of its symbols are injected into the user’s namespace. The usage is similar to that of %%cython_pyximport but you don’t have to pass a module name:

%%cython
def f(x):
    return 2.0*x

To compile OpenMP codes, pass the required –compile-args and –link-args. For example with gcc:

%%cython --compile-args=-fopenmp --link-args=-fopenmp
...
optional arguments:
-c COMPILE_ARGS, --compile-args COMPILE_ARGS
 Extra flags to pass to compiler via the extra_compile_args Extension flag (can be specified multiple times).
--link-args LINK_ARGS
 Extra flags to pass to linker via the extra_link_args Extension flag (can be specified multiple times).
-l LIB, --lib LIB
 Add a library to link the extension against (can be specified multiple times).
-n NAME, --name NAME
 Specify a name for the Cython module.
-L dir Add a path to the list of libary directories (can be specified multiple times).
-I INCLUDE, --include INCLUDE
 Add a path to the list of include directories (can be specified multiple times).
--cplus Output a C++ rather than C file.
-f, --force Force the compilation of a new module, even if the source has been previously compiled.
-a, --annotate Produce a colorized HTML version of the source.

%%cython_inline

Compile and run a Cython code cell using Cython.inline.

This magic simply passes the body of the cell to Cython.inline and returns the result. If the variables a and b are defined in the user’s namespace, here is a simple example that returns their sum:

%%cython_inline
return a+b

For most purposes, we recommend the usage of the %%cython magic.

%%cython_pyximport

Compile and import a Cython code cell using pyximport.

The contents of the cell are written to a .pyx file in the current working directory, which is then imported using pyximport. This magic requires a module name to be passed:

%%cython_pyximport modulename
def f(x):
    return 2.0*x

The compiled module is then imported and all of its symbols are injected into the user’s namespace. For most purposes, we recommend the usage of the %%cython magic.

Author: * Brian Granger

Parts of this code were taken from Cython.inline.