9 Cython code, unlike Python, must be compiled. This happens in two stages:
11 * A ``.pyx`` file is compiles by Cython to a ``.c`` file.
13 * The ``.c`` file is compiled by a C compiler to a ``.so`` file (or a
14 ``.pyd`` file on Windows)
17 The following sub-sections describe several ways to build your
18 extension modules, and how to pass directives to the Cython compiler.
20 Compiling from the command line
21 ===============================
23 Run the Cython compiler command with your options and list of ``.pyx``
24 files to generate. For example::
26 $ cython -a yourmod.pyx
28 This creates a ``yourmod.c`` file, and the -a switch produces a
29 generated html file. Pass the ``-h`` flag for a complete list of
32 Compiling your ``.c`` files will vary depending on your operating
33 system. Python documentation for writing extension modules should
34 have some details for your system. Here we give an example on a Linux
37 $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.5 -o yourmod.so yourmod.c
39 [``gcc`` will need to have paths to your included header files and
40 paths to libraries you need to link with]
42 A ``yourmod.so`` file is now in the same directory and your module,
43 ``yourmod``, is available for you to import as you normally would.
45 Compiling with ``distutils``
46 ============================
48 First, make sure that ``distutils`` package is installed in your
49 system. The following assumes a Cython file to be compiled called
50 *hello.pyx*. Now, create a ``setup.py`` script::
52 from distutils.core import setup
53 from distutils.extension import Extension
54 from Cython.Distutils import build_ext
56 ext_modules = [Extension("spam", ["spam.pyx"]),
57 Extension("ham", ["ham.pyx"])]
58 # You can add directives for each extension too
59 # by attaching the `pyrex_directives`
61 e.pyrex_directives = {"boundscheck": False}
63 name = "My hello app",
64 cmdclass = {"build_ext": build_ext},
65 ext_modules = ext_modules
68 Run the command ``python setup.py build_ext --inplace`` in your
69 system's command shell and you are done. Import your new extension
70 module into your python shell or script as normal.
72 Cython provides utility code to automatically generate lists of
73 Extension objects from ```.pyx`` files, so one can write::
75 from distutils.core import setup
76 from Cython.Build import cythonize
79 name = "My hello app",
80 ext_modules = cythonize("*.pyx"),
83 to compile all ``.pyx`` files in a given directory.
84 The ``cythonize`` command also allows for multi-threaded compilation and
85 dependency resolution.
87 Compiling with ``pyximport``
88 =============================
90 For generating Cython code right in your pure python module just type::
92 >>> import pyximport; pyximport.install()
96 This allows you to automatically run Cython on every ``.pyx`` that
97 Python is trying to import. You should use this for simple Cython
98 builds only where no extra C libraries and no special building setup
101 In the case that Cython fails to compile a Python module, *pyximport*
102 will fall back to loading the source modules instead.
104 It is also possible to compile new ``.py`` modules that are being
105 imported (including the standard library and installed packages). For
106 using this feature, just tell that to ``pyximport``::
108 >>> pyximport.install(pyimport = True)
110 Compiling with ``cython.inline``
111 =============================
113 One can also compile Cython in a fashion similar to SciPy's ``weave.inline``.
118 ... ret = cython.inline("return a+b", b=3)
121 Unbound variables are automatically pulled from the surrounding local
122 and global scopes, and the result of the compilation is cached for
128 The Sage notebook allows transparently editing and compiling Cython
129 code simply by typing ``%cython`` at the top of a cell and evaluate
130 it. Variables and functions defined in a Cython cell are imported into the
131 running session. Please check `Sage documentation
132 <http://www.sagemath.org/doc/>`_ for details.
134 You can tailor the behavior of the Cython compiler by specifying the
141 Compiler directives are instructions which affect the behavior of
142 Cython code. Here is the list of currently supported directives:
144 ``boundscheck`` (True / False)
145 If set to False, Cython is free to assume that indexing operations
146 ([]-operator) in the code will not cause any IndexErrors to be
147 raised. Currently this is only made use of for buffers, lists and
148 tuples, but could be affected other types in the future. Conditions
149 which would normally trigger an IndexError may instead cause
150 segfaults or data corruption if this is set to False.
153 ``wraparound`` (True / False)
154 In Python arrays can be indexed relative to the end. For example
155 A[-1] indexes the last value of a list. In C negative indexing is
156 not supported. If set to False, Cython will neither check for nor
157 correctly handle negative indices, possibly causing segfaults or
161 ``nonecheck`` (True / False)
162 If set to False, Cython is free to assume that native field
163 accesses on variables typed as an extension type, or buffer
164 accesses on a buffer variable, never occurs when the variable is
165 set to ``None``. Otherwise a check is inserted and the
166 appropriate exception is raised. This is off by default for
167 performance reasons. Default is False.
169 ``embedsignature`` (True / False)
170 If set to True, Cython will embed a textual copy of the call
171 signature in the docstring of all Python visible functions and
172 classes. Tools like IPython and epydoc can thus display the
173 signature, which cannot otherwise be retrieved after
174 compilation. Default is False.
176 ``cdivision`` (True / False)
177 If set to False, Cython will adjust the remainder and quotient
178 operators C types to match those of Python ints (which differ when
179 the operands have opposite signs) and raise a
180 ``ZeroDivisionError`` when the right operand is 0. This has up to
181 a 35% speed penalty. If set to True, no checks are performed. See
182 `CEP 516 <http://wiki.cython.org/enhancements/division>`_. Default
185 ``cdivision_warnings`` (True / False)
186 If set to True, Cython will emit a runtime warning whenever
187 division is performed with negative operands. See `CEP 516
188 <http://wiki.cython.org/enhancements/division>`_. Default is
191 ``always_allow_keywords`` (True / False)
192 Avoid the ``METH_NOARGS`` and ``METH_O`` when constructing
193 functions/methods which take zero or one arguments. Has no effect
194 on special methods and functions with more than one argument. The
195 ``METH_NOARGS`` and ``METH_O`` signatures provide faster
196 calling conventions but disallow the use of keywords.
198 ``profile`` (True / False)
199 Add hooks for Python profilers into the compiled C code. Default
202 ``infer_types`` (True / False)
203 Infer types of untyped variables in function bodies. Default is
204 None, indicating that on safe (semantically-unchanging) inferences
207 How to set directives
208 ---------------------
213 One can set compiler directives through a special header comment at the top of the file, like this::
216 #cython: boundscheck=False
218 The comment must appear before any code (but can appear after other
219 comments or whitespace).
221 One can also pass a directive on the command line by using the -X switch::
223 $ cython -X boundscheck=True ...
225 Directives passed on the command line will override directives set in
231 For local blocks, you need to cimport the special builtin ``cython``
237 Then you can use the directives either as decorators or in a with
238 statement, like this::
241 @cython.boundscheck(False) # turn off boundscheck for this function
244 with cython.boundscheck(True): # turn it temporarily on again for this block
247 .. Warning:: These two methods of setting directives are **not**
248 affected by overriding the directive on the command-line using the