Merged pull request #12 from bhy/T423.
[cython.git] / docs / src / userguide / pyrex_differences.rst
1 .. highlight:: cython
2
3 .. _pyrex-differences:
4
5 **************************************
6 Differences between Cython and Pyrex
7 **************************************
8
9 .. warning:: 
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. 
17
18
19 Python 3.0 Support
20 ==================
21
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. 
26
27 Many Python 3 constructs are already supported by Cython. 
28
29 List/Set/Dict Comprehensions
30 ----------------------------
31
32 Cython supports the different comprehensions defined by Python 3.0 for
33 lists, sets and dicts::
34
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
38
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``).
43
44 .. note:: see :ref:`automatic-range-conversion`
45
46 Note that Cython also supports set literals starting from Python 2.3.
47
48 Keyword-only arguments
49 ----------------------
50
51 Python functions can have keyword-only arguments listed after the ``*``
52 parameter and before the ``**`` parameter if any, e.g.::
53
54     def f(a, b, *args, c, d = 42, e, **kwds):
55         ...
56
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.
60
61 If the parameter name after the ``*`` is omitted, the function will not accept any
62 extra positional arguments, e.g.::
63
64     def g(a, b, *, c, d):
65         ...
66
67 takes exactly two positional parameters and has two required keyword parameters.
68
69
70
71 Conditional expressions "x if b else y" (python 2.5)
72 =====================================================
73
74 Conditional expressions as described in
75 http://www.python.org/dev/peps/pep-0308/::
76
77     X if C else Y
78        
79 Only one of ``X`` and ``Y`` is evaluated, (depending on the value of C). 
80
81 cdef inline
82 =============
83
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.::
86
87     cdef inline int something_fast(int a, int b):
88         return a*a + b
89        
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
92 cases. 
93
94 Assignment on declaration (e.g. "cdef int spam = 5")
95 ======================================================
96
97 In Pyrex, one must write::
98
99     cdef int i, j, k
100     i = 2
101     j = 5
102     k = 7
103     
104 Now, with cython, one can write::
105
106     cdef int i = 2, j = 5, k = 7
107     
108 The expression on the right hand side can be arbitrarily complicated, e.g.::
109
110     cdef int n = python_call(foo(x,y), a + b + c) - 32
111        
112
113 'by' expression in for loop (e.g. "for i from 0 <= i < 10 by 2")
114 ==================================================================
115     
116 ::
117
118     for i from 0 <= i < 10 by 2:
119         print i
120        
121
122 yields::
123
124     0
125     2
126     4
127     6
128     8
129
130 .. note:: see :ref:`automatic-range-conversion`
131        
132
133 Boolean int type (e.g. it acts like a c int, but coerces to/from python as a boolean)
134 ======================================================================================
135
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::
143
144     def is_equal(x):
145         return x == y
146
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::
150
151     cdef int i = x
152     cdef bint b = x
153
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.) 
157
158 Executable class bodies
159 =======================
160
161 Including a working :func:`classmethod`::
162
163     cdef class Blah:
164         def some_method(self):
165             print self
166         some_method = classmethod(some_method)
167         a = 2*3
168         print "hi", a
169         
170 cpdef functions
171 =================
172
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::
182
183     if type(self) has a __dict__:
184         foo = self.getattr('foo')
185         if foo is not wrapper_foo:
186             return foo(args)
187     [cdef method body]
188
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.::
197
198     cdef class A:
199         cpdef foo(self):
200             pass
201
202     x = A()
203     x.foo()  # will check to see if overridden
204     A.foo(x) # will call A's implementation whether overridden or not
205
206 See :ref:`early-binding-for-speed` for explanation and usage tips. 
207
208 .. _automatic-range-conversion:
209
210 Automatic range conversion
211 ============================
212
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. 
216
217 .. warning:: 
218
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
224     way to set this).
225
226 More friendly type casting
227 ===========================
228
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.
233
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.
238
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`. 
243
244 Optional arguments in cdef/cpdef functions
245 ============================================
246
247 Cython now supports optional arguments for :keyword:`cdef` and
248 :keyword:`cpdef` functions.
249
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. 
256
257 For example, one can have the ``.pxd`` file::
258
259     cdef class A:
260         cdef foo(self)
261     cdef class B(A)
262         cdef foo(self, x=*)
263     cdef class C(B):
264         cpdef foo(self, x=*, int k=*)
265
266 with corresponding ``.pyx`` file::
267
268     cdef class A:
269         cdef foo(self):
270             print "A"
271     cdef class B(A)
272         cdef foo(self, x=None)
273             print "B", x
274     cdef class C(B):
275         cpdef foo(self, x=True, int k=3)
276             print "C", x, k
277
278 .. note:: 
279
280     this also demonstrates how :keyword:`cpdef` functions can override
281     :keyword:`cdef` functions.
282
283 Function pointers in structs
284 =============================
285
286 Functions declared in :keyword:`structs` are automatically converted to
287 function pointers for convenience.
288
289 C++ Exception handling
290 =========================
291
292 :keyword:`cdef` functions can now be declared as::
293
294     cdef int foo(...) except +
295     cdef int foo(...) except +TypeError
296     cdef int foo(...) except +python_error_raising_function
297
298 in which case a Python exception will be raised when a C++ error is caught.
299 See :ref:`wrapping-cplusplus` for more details.
300
301 Synonyms
302 =========
303
304 ``cdef import from`` means the same thing as ``cdef extern from``
305
306 Source code encoding
307 ======================
308
309 .. TODO: add the links to the relevent PEPs
310
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.
315
316 Automatic ``typecheck``
317 ========================
318
319 Rather than introducing a new keyword :keyword:`typecheck` as explained in the
320 `Pyrex docs
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.
324
325 From __future__ directives
326 ==========================
327
328 Cython supports several from __future__ directives, namely ``unicode_literals`` and ``division``. 
329
330 With statements are always enabled. 
331
332 Pure Python mode
333 ================
334
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 
339 optimized results. 
340 See http://wiki.cython.org/pure 
341 for more details. 
342