Merged pull request #12 from bhy/T423.
[cython.git] / docs / src / reference / compilation.rst
1 .. highlight:: cython
2
3 .. _compilation:
4
5 =============
6 Compilation
7 =============
8
9 Cython code, unlike Python, must be compiled.  This happens in two stages:
10
11   * A ``.pyx`` file is compiles by Cython to a ``.c`` file.
12
13   * The ``.c`` file is compiled by a C compiler to a ``.so`` file (or a
14     ``.pyd`` file on Windows)
15
16
17 The following sub-sections describe several ways to build your
18 extension modules, and how to pass directives to the Cython compiler.
19
20 Compiling from the command line
21 ===============================
22
23 Run the Cython compiler command with your options and list of ``.pyx``
24 files to generate.  For example::
25
26     $ cython -a yourmod.pyx
27
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
30 supported flags.
31
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
35 system::
36
37     $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.5 -o yourmod.so yourmod.c
38
39 [``gcc`` will need to have paths to your included header files and
40 paths to libraries you need to link with]
41
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.
44
45 Compiling with ``distutils``
46 ============================
47
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::
51
52     from distutils.core import setup
53     from distutils.extension import Extension
54     from Cython.Distutils import build_ext
55
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`
60     for e in ext modules:
61         e.pyrex_directives = {"boundscheck": False}
62     setup(
63         name = "My hello app",
64         cmdclass = {"build_ext": build_ext},
65         ext_modules = ext_modules
66     )
67
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.
71
72 Cython provides utility code to automatically generate lists of
73 Extension objects from ```.pyx`` files, so one can write::
74
75     from distutils.core import setup
76     from Cython.Build import cythonize
77
78     setup(
79         name = "My hello app",
80         ext_modules = cythonize("*.pyx"),
81     )
82
83 to compile all ``.pyx`` files in a given directory.
84 The ``cythonize`` command also allows for multi-threaded compilation and
85 dependency resolution.
86
87 Compiling with ``pyximport``
88 =============================
89
90 For generating Cython code right in your pure python module just type::
91
92     >>> import pyximport; pyximport.install()
93     >>> import helloworld  
94     Hello World
95
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
99 is needed.
100
101 In the case that Cython fails to compile a Python module, *pyximport*
102 will fall back to loading the source modules instead.
103
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``::
107
108     >>> pyximport.install(pyimport = True)
109
110 Compiling with ``cython.inline``
111 =============================
112
113 One can also compile Cython in a fashion similar to SciPy's ``weave.inline``.
114 For example::
115
116     >>> import cython
117     >>> def f(a):
118     ...     ret = cython.inline("return a+b", b=3)
119     ... 
120
121 Unbound variables are automatically pulled from the surrounding local
122 and global scopes, and the result of the compilation is cached for
123 efficient re-use.
124
125 Compiling with Sage
126 ===================
127
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.
133
134 You can tailor the behavior of the Cython compiler by specifying the
135 directives below.
136
137 ====================
138 Compiler directives
139 ====================
140
141 Compiler directives are instructions which affect the behavior of
142 Cython code.  Here is the list of currently supported directives:
143
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.
151     Default is True.
152
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
158     data corruption.
159     Default is True.
160
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.
168
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.
175
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
183     is False.
184
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
189     False.
190
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.
197
198 ``profile`` (True / False)
199     Add hooks for Python profilers into the compiled C code.  Default
200     is False.
201
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
205    are allowed.
206
207 How to set directives
208 ---------------------
209
210 Globally
211 :::::::::
212
213 One can set compiler directives through a special header comment at the top of the file, like this::
214
215     #!python
216     #cython: boundscheck=False
217
218 The comment must appear before any code (but can appear after other
219 comments or whitespace).
220
221 One can also pass a directive on the command line by using the -X switch::
222
223     $ cython -X boundscheck=True ...
224
225 Directives passed on the command line will override directives set in
226 header comments.
227
228 Locally
229 ::::::::
230
231 For local blocks, you need to cimport the special builtin ``cython``
232 module::
233
234     #!python
235     cimport cython
236
237 Then you can use the directives either as decorators or in a with
238 statement, like this::
239
240     #!python
241     @cython.boundscheck(False) # turn off boundscheck for this function
242     def f():
243         ...
244         with cython.boundscheck(True): # turn it temporarily on again for this block
245             ...
246
247 .. Warning:: These two methods of setting directives are **not**
248     affected by overriding the directive on the command-line using the
249     -X option.