5 **************************************
6 Differences between Cython and Pyrex
7 **************************************
10 Both Cython and Pyrex are moving targets. It has come to the point
11 that an explicit list of all the differences between the two
12 projects would be laborious to list and track, but hopefully
13 this high-level list gives an idea of the differences that
14 are present. It should be noted that both projects make an effort
15 at mutual compatibility, but Cython's goal is to be as close to
16 and complete as Python as reasonable.
22 Cython creates ``.c`` files that can be built and used with both
23 Python 2.x and Python 3.x. In fact, compiling your module with
24 Cython may very well be the easiest way to port code to Python 3.0.
25 We are also working to make the compiler run in both Python 2.x and 3.0.
27 Many Python 3 constructs are already supported by Cython.
29 List/Set/Dict Comprehensions
30 ----------------------------
32 Cython supports the different comprehensions defined by Python 3.0 for
33 lists, sets and dicts::
35 [expr(x) for x in A] # list
36 {expr(x) for x in A} # set
37 {key(x) : value(x) for x in A} # dict
39 Looping is optimized if ``A`` is a list, tuple or dict. You can use
40 the :keyword:`for` ... :keyword:`from` syntax, too, but it is
41 generally preferred to use the usual :keyword:`for` ... :keyword:`in`
42 ``range(...)`` syntax with a C run variable (e.g. ``cdef int i``).
44 .. note:: see :ref:`automatic-range-conversion`
46 Note that Cython also supports set literals starting from Python 2.3.
48 Keyword-only arguments
49 ----------------------
51 Python functions can have keyword-only arguments listed after the ``*``
52 parameter and before the ``**`` parameter if any, e.g.::
54 def f(a, b, *args, c, d = 42, e, **kwds):
57 Here ``c``, ``d`` and ``e`` cannot be passed as position arguments and must be
58 passed as keyword arguments. Furthermore, ``c`` and ``e`` are required keyword
59 arguments, since they do not have a default value.
61 If the parameter name after the ``*`` is omitted, the function will not accept any
62 extra positional arguments, e.g.::
67 takes exactly two positional parameters and has two required keyword parameters.
71 Conditional expressions "x if b else y" (python 2.5)
72 =====================================================
74 Conditional expressions as described in
75 http://www.python.org/dev/peps/pep-0308/::
79 Only one of ``X`` and ``Y`` is evaluated, (depending on the value of C).
84 Module level functions can now be declared inline, with the :keyword:`inline`
85 keyword passed on to the C compiler. These can be as fast as macros.::
87 cdef inline int something_fast(int a, int b):
90 Note that class-level :keyword:`cdef` functions are handled via a virtual
91 function table, so the compiler won't be able to inline them in almost all
94 Assignment on declaration (e.g. "cdef int spam = 5")
95 ======================================================
97 In Pyrex, one must write::
104 Now, with cython, one can write::
106 cdef int i = 2, j = 5, k = 7
108 The expression on the right hand side can be arbitrarily complicated, e.g.::
110 cdef int n = python_call(foo(x,y), a + b + c) - 32
113 'by' expression in for loop (e.g. "for i from 0 <= i < 10 by 2")
114 ==================================================================
118 for i from 0 <= i < 10 by 2:
130 .. note:: see :ref:`automatic-range-conversion`
133 Boolean int type (e.g. it acts like a c int, but coerces to/from python as a boolean)
134 ======================================================================================
136 In C, ints are used for truth values. In python, any object can be used as a
137 truth value (using the :meth:`__nonzero__` method, but the canonical choices
138 are the two boolean objects ``True`` and ``False``. The :keyword:`bint` of
139 "boolean int" object is compiled to a C int, but get coerced to and from
140 Cython as booleans. The return type of comparisons and several builtins is a
141 :ctype:`bint` as well. This allows one to avoid having to wrap things in
142 :func:`bool()`. For example, one can write::
147 which would return ``1`` or ``0`` in Pyrex, but returns ``True`` or ``False`` in
148 python. One can declare variables and return values for functions to be of the
149 :ctype:`bint` type. For example::
154 The first conversion would happen via ``x.__int__()`` whereas the second would
155 happen via ``x.__nonzero__()``. (Actually, if ``x`` is the python object
156 ``True`` or ``False`` then no method call is made.)
158 Executable class bodies
159 =======================
161 Including a working :func:`classmethod`::
164 def some_method(self):
166 some_method = classmethod(some_method)
173 Cython adds a third function type on top of the usual :keyword:`def` and
174 :keyword:`cdef`. If a function is declared :keyword:`cpdef` it can be called
175 from and overridden by both extension and normal python subclasses. You can
176 essentially think of a :keyword:`cpdef` method as a :keyword:`cdef` method +
177 some extras. (That's how it's implemented at least.) First, it creates a
178 :keyword:`def` method that does nothing but call the underlying
179 :keyword:`cdef` method (and does argument unpacking/coercion if needed). At
180 the top of the :keyword:`cdef` method a little bit of code is added to check
181 to see if it's overridden. Specifically, in pseudocode::
183 if type(self) has a __dict__:
184 foo = self.getattr('foo')
185 if foo is not wrapper_foo:
189 To detect whether or not a type has a dictionary, it just checks the
190 tp_dictoffset slot, which is ``NULL`` (by default) for extension types, but
191 non- null for instance classes. If the dictionary exists, it does a single
192 attribute lookup and can tell (by comparing pointers) whether or not the
193 returned result is actually a new function. If, and only if, it is a new
194 function, then the arguments packed into a tuple and the method called. This
195 is all very fast. A flag is set so this lookup does not occur if one calls the
196 method on the class directly, e.g.::
203 x.foo() # will check to see if overridden
204 A.foo(x) # will call A's implementation whether overridden or not
206 See :ref:`early-binding-for-speed` for explanation and usage tips.
208 .. _automatic-range-conversion:
210 Automatic range conversion
211 ============================
213 This will convert statements of the form ``for i in range(...)`` to ``for i
214 from ...`` when ``i`` is any cdef'd integer type, and the direction (i.e. sign
215 of step) can be determined.
219 This may change the semantics if the range causes
220 assignment to ``i`` to overflow. Specifically, if this option is set, an error
221 will be raised before the loop is entered, whereas without this option the loop
222 will execute until a overflowing value is encountered. If this effects you
223 change ``Cython/Compiler/Options.py`` (eventually there will be a better
226 More friendly type casting
227 ===========================
229 In Pyrex, if one types ``<int>x`` where ``x`` is a Python object, one will get
230 the memory address of ``x``. Likewise, if one types ``<object>i`` where ``i``
231 is a C int, one will get an "object" at location ``i`` in memory. This leads
232 to confusing results and segfaults.
234 In Cython ``<type>x`` will try and do a coercion (as would happen on assignment of
235 ``x`` to a variable of type type) if exactly one of the types is a python object.
236 It does not stop one from casting where there is no conversion (though it will
237 emit a warning). If one really wants the address, cast to a ``void *`` first.
239 As in Pyrex ``<MyExtensionType>x`` will cast ``x`` to type :ctype:`MyExtensionType` without any
240 type checking. Cython supports the syntax ``<MyExtensionType?>`` to do the cast
241 with type checking (i.e. it will throw an error if ``x`` is not a (subclass of)
242 :ctype:`MyExtensionType`.
244 Optional arguments in cdef/cpdef functions
245 ============================================
247 Cython now supports optional arguments for :keyword:`cdef` and
248 :keyword:`cpdef` functions.
250 The syntax in the ``.pyx`` file remains as in Python, but one declares such
251 functions in the ``.pxd`` file by writing ``cdef foo(x=*)``. The number of
252 arguments may increase on subclassing, but the argument types and order must
253 remain the same. There is a slight performance penalty in some cases when a
254 cdef/cpdef function without any optional is overridden with one that does have
255 default argument values.
257 For example, one can have the ``.pxd`` file::
264 cpdef foo(self, x=*, int k=*)
266 with corresponding ``.pyx`` file::
272 cdef foo(self, x=None)
275 cpdef foo(self, x=True, int k=3)
280 this also demonstrates how :keyword:`cpdef` functions can override
281 :keyword:`cdef` functions.
283 Function pointers in structs
284 =============================
286 Functions declared in :keyword:`structs` are automatically converted to
287 function pointers for convenience.
289 C++ Exception handling
290 =========================
292 :keyword:`cdef` functions can now be declared as::
294 cdef int foo(...) except +
295 cdef int foo(...) except +TypeError
296 cdef int foo(...) except +python_error_raising_function
298 in which case a Python exception will be raised when a C++ error is caught.
299 See :ref:`wrapping-cplusplus` for more details.
304 ``cdef import from`` means the same thing as ``cdef extern from``
307 ======================
309 .. TODO: add the links to the relevent PEPs
311 Cython supports PEP 3120 and PEP 263, i.e. you can start your Cython source
312 file with an encoding comment and generally write your source code in UTF-8.
313 This impacts the encoding of byte strings and the conversion of unicode string
314 literals like ``u'abcd'`` to unicode objects.
316 Automatic ``typecheck``
317 ========================
319 Rather than introducing a new keyword :keyword:`typecheck` as explained in the
321 <http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/Manual/special_methods.html>`_,
322 Cython emits a (non-spoofable and faster) typecheck whenever
323 :func:`isinstance` is used with an extension type as the second parameter.
325 From __future__ directives
326 ==========================
328 Cython supports several from __future__ directives, namely ``unicode_literals`` and ``division``.
330 With statements are always enabled.
335 Cython has support for compiling ``.py`` files, and
336 accepting type annotations using decorators and other
337 valid Python syntax. This allows the same source to
338 be interpreted as straight Python, or compiled for
340 See http://wiki.cython.org/pure