1 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
4 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
7 <meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]">
8 <title>Cython Language Overview</title>
12 <h1> <hr width="100%">Overview of the Cython Language <hr width="100%"></h1>
14 This document informally describes the extensions to the Python language
15 made by Cython. Some day there will be a reference manual covering everything
24 <li> <a href="#Basics">Basics</a></li>
26 <li> <a href="#PyFuncsVsCFuncs">Python functions vs. C functions</a></li>
27 <li> <a href="#PyObjParams">Python objects as parameters</a></li>
28 <li> <a href="#CVarAndTypeDecls">C variable and type definitions</a></li><li><a href="#AutomaticTypeConversions">Automatic type conversions</a></li>
30 <li><a href="#PyToCStringCaveats">Caveats when using a Python string in a C context</a></li>
33 <li> <a href="#ScopeRules">Scope rules</a></li>
34 <li> <a href="#StatsAndExprs">Statements and expressions</a></li>
36 <li> <a href="#ExprSyntaxDifferences">Differences between C and Cython
39 <li> <a href="#ForFromLoop">Integer for-loops</a></li>
41 <li> <a href="#ExceptionValues">Error return values</a></li>
43 <li> <a href="#CheckingReturnValues">Checking return values of non-Cython
46 <li> <a href="#IncludeStatement">The <tt>include</tt> statement</a></li>
48 <li> <a href="#InterfacingWithExternal">Interfacing with External C Code</a></li>
50 <li> <a href="#ExternDecls">External declarations</a></li>
52 <li> <a href="#ReferencingHeaders">Referencing C header files</a></li>
53 <li> <a href="#StructDeclStyles">Styles of struct/union/enum declaration</a></li>
54 <li> <a href="#AccessingAPI">Accessing Python/C API routines</a></li>
55 <li> <a href="#CNameSpecs">Resolving naming conflicts - C name specifications</a></li>
57 <li> <a href="#PublicDecls">Public declarations</a></li>
59 <li> <a href="extension_types.html">Extension Types</a> <font color="#006600">(Section revised in 0.9)</font></li>
60 <li> <a href="sharing.html">Sharing Declarations Between Cython Modules</a>
61 <font color="#006600">(NEW in 0.8)</font></li>
62 <li> <a href="#Limitations">Limitations</a></li>
64 <li> <a href="#Unsupported">Unsupported Python features</a></li>
65 <li> <a href="#SemanticDifferences">Semantic differences between Python
72 <h2> <hr width="100%"><a name="Basics"></a>Basics
73 <hr width="100%"></h2>
75 This section describes the basic features of the Cython language. The facilities
76 covered in this section allow you to create Python-callable functions that
77 manipulate C data structures and convert between Python and C data types.
78 Later sections will cover facilities for <a href="#InterfacingWithExternal">wrapping external C code</a>, <a href="extension_types.html">creating new Python types</a> and <a href="sharing.html">cooperation between Cython modules</a>.
79 <h3> <a name="PyFuncsVsCFuncs"></a>Python functions vs. C functions</h3>
81 There are two kinds of function definition in Cython:
82 <p><b>Python functions</b> are defined using the <b>def</b> statement, as
83 in Python. They take Python objects as parameters and return Python objects.
87 <p><b>C functions</b> are defined using the new <b>cdef</b> statement. They
88 take either Python objects or C values as parameters, and can return either
89 Python objects or C values. </p>
92 <p>Within a Cython module, Python functions and C functions can call each other
93 freely, but only Python functions can be called from outside the module by
94 interpreted Python code. So, any functions that you want to "export" from
95 your Cython module must be declared as Python functions using <span style="font-weight: bold;">def</span>. </p>
98 <p>Parameters of either type of function can be declared to have C data types,
99 using normal C declaration syntax. For example, </p>
102 <blockquote> <pre>def spam(int i, char *s):<br> ...</pre>
103 <pre>cdef int eggs(unsigned long l, float f):<br> ...</pre>
106 When a parameter of a Python function is declared to have a C data type,
107 it is passed in as a Python object and automatically converted to a C value,
108 if possible. Automatic conversion is currently only possible for numeric
109 types and string types; attempting to use any other type for the parameter
110 of a Python function will result in a compile-time error.
111 <p>C functions, on the other hand, can have parameters of any type, since
112 they're passed in directly using a normal C function call. </p>
115 <h3> <a name="PyObjParams"></a>Python objects as parameters and return values</h3>
117 If no type is specified for a parameter or return value, <i>it is assumed
118 to be a Python object.</i> (Note that this is different from the C convention,
119 where it would default to <tt>int</tt>.) For example, the following defines
120 a C function that takes two Python objects as parameters and returns a Python
122 <blockquote> <pre>cdef spamobjs(x, y):<br> ...</pre>
125 Reference counting for these objects is performed automatically according
126 to the standard Python/C API rules (i.e. borrowed references are taken as
127 parameters and a new reference is returned).
128 <p>The name <b>object</b> can also be used to explicitly declare something
129 as a Python object. This can be useful if the name being declared would otherwise
130 be taken as the name of a type, for example, </p>
133 <blockquote> <pre>cdef ftang(object int):<br> ...</pre>
136 declares a parameter called <tt>int</tt> which is a Python object. You
137 can also use <b>object </b>as the explicit return type of a function, e.g.
139 <blockquote> <pre>cdef object ftang(object int):<br> ...</pre>
142 In the interests of clarity, it is probably a good idea to always be explicit
143 about <b>object </b>parameters in C functions.
144 <h3> <a name="CVarAndTypeDecls"></a>C variable and type definitions</h3>
146 The <b>cdef</b> statement is also used to declare C variables, either
147 local or module-level:
148 <blockquote> <pre>cdef int i, j, k<br>cdef float f, g[42], *h</pre>
151 and C struct, union or enum types:
152 <blockquote> <pre>cdef struct Grail:<br> int age<br> float volume</pre>
153 <pre>cdef union Food:<br> char *spam<br> float *eggs</pre>
154 <pre>cdef enum CheeseType:<br> cheddar, edam, <br> camembert</pre>
155 <pre>cdef enum CheeseState:<br> hard = 1<br> soft = 2<br> runny = 3</pre>
158 There is currently no special syntax for defining a constant, but you
159 can use an anonymous enum declaration for this purpose, for example,
160 <blockquote><tt>cdef enum:</tt> <br>
161 <tt> tons_of_spam = 3</tt></blockquote>
163 Note that the words <span style="font-family: monospace;">struct</span>, <span style="font-family: monospace;">union</span> and <span style="font-family: monospace;">enum</span> are used only when <i>defining</i> a type, not when referring to it. For example, to declare a variable pointing
164 to a Grail you would write
165 <blockquote> <pre>cdef Grail *gp</pre>
169 <blockquote> <pre>cdef struct Grail *gp <font color="#ed181e"># WRONG</font></pre>
172 There is also a <b>ctypedef</b> statement for giving names to types, e.g.
174 <blockquote> <pre>ctypedef unsigned long ULong</pre>
175 <pre>ctypedef int *IntPtr<br></pre></blockquote>
177 <h3><a name="AutomaticTypeConversions"></a>Automatic type conversions</h3>
179 In most situations, automatic conversions will be performed for the
180 basic numeric and string types when a Python object is used in a
181 context requiring a C value, or vice versa. The following table
182 summarises the conversion possibilities.<br>
186 <table style="margin-left: auto; margin-right: auto; width: 10%; text-align: left;" border="1" cellpadding="4" cellspacing="0">
190 <th style="vertical-align: top; width: 40%; white-space: nowrap;">C types<br>
192 <th style="vertical-align: top; width: 150px; white-space: nowrap;">From Python types<br>
194 <th style="vertical-align: top; width: 150px; white-space: nowrap;">To Python types<br>
198 <td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">[unsigned] char<br>
201 <td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int, long<br>
203 <td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int<br>
210 <td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">unsigned int<br>
212 [unsigned] long long<br>
215 <td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">int, long<br>
219 <td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">long<br>
230 <td style="vertical-align: top; width: 40%; white-space: nowrap;">float, double, long double<br>
232 <td style="vertical-align: top; width: 150px; white-space: nowrap;">int, long, float<br>
234 <td style="vertical-align: top; width: 150px; white-space: nowrap;">float<br>
238 <td style="vertical-align: top; width: 40%; white-space: nowrap;">char *<br>
240 <td style="vertical-align: top; width: 150px; white-space: nowrap;">str<span style="font-style: italic;"></span><br>
242 <td style="vertical-align: top; width: 150px; white-space: nowrap;">str<br>
250 <h4><a name="PyToCStringCaveats"></a>Caveats when using a Python string in a C context</h4>
252 You need to be careful when using a Python string in a context expecting a <span style="font-family: monospace;">char *</span>.
253 In this situation, a pointer to the contents of the Python string is
254 used, which is only valid as long as the Python string exists. So you
255 need to make sure that a reference to the original Python string is
256 held for as long as the C string is needed. If you can't guarantee that
257 the Python string will live long enough, you will need to copy the C
262 Cython detects and prevents <span style="font-style: italic;">some</span> mistakes of this kind. For instance, if you attempt something like<br>
264 <pre style="margin-left: 40px;">cdef char *s<br>s = pystring1 + pystring2</pre>
266 then Cython will produce the error message "<span style="font-weight: bold;">Obtaining char * from temporary Python value</span>".
267 The reason is that concatenating the two Python strings produces a new
268 Python string object that is referenced only by a temporary internal
269 variable that Cython generates. As soon as the statement has finished,
270 the temporary variable will be decrefed and the Python string
271 deallocated, leaving <span style="font-family: monospace;">s</span> dangling. Since this code could not possibly work, Cython refuses to compile it.<br>
275 The solution is to assign the result of the concatenation to a Python variable, and then obtain the char * from that, i.e.<br>
277 <pre style="margin-left: 40px;">cdef char *s<br>p = pystring1 + pystring2<br>s = p<br></pre>
279 It is then your responsibility to hold the reference <span style="font-family: monospace;">p</span> for as long as necessary.<br>
283 Keep in mind that the rules used to detect such errors are only
284 heuristics. Sometimes Cython will complain unnecessarily, and sometimes
285 it will fail to detect a problem that exists. Ultimately, you need to
286 understand the issue and be careful what you do.<br>
293 <h3> <a name="ScopeRules"></a>Scope rules</h3>
295 Cython determines whether a variable belongs to a local scope, the module
296 scope, or the built-in scope <i>completely statically.</i> As with Python,
297 assigning to a variable which is not otherwise declared implicitly declares
298 it to be a Python variable residing in the scope where it is assigned. Unlike
299 Python, however, a name which is referred to but not declared or assigned
300 is assumed to reside in the <i>builtin scope, </i>not the module scope.
301 Names added to the module dictionary at run time will not shadow such names.
303 <p>You can use a <b>global</b> statement at the module level to explicitly
304 declare a name to be a module-level name when there would otherwise not be
305 any indication of this, for example, </p>
308 <blockquote><tt>global __name__</tt> <br>
309 <tt>print __name__</tt></blockquote>
311 Without the <b>global</b> statement, the above would print the name of
312 the builtins module.<br>
316 Note: A consequence of these rules is that the module-level scope behaves
317 the same way as a Python local scope if you refer to a variable before assigning
318 to it. In particular, tricks such as the following will <i>not</i> work
322 <blockquote> <pre>try:<br> x = True<br>except NameError:<br> True = 1<br></pre>
325 because, due to the assignment, the True will always be looked up in the
326 module-level scope. You would have to do something like this instead:<br>
329 <blockquote> <pre>import __builtin__<br>try:<br> True = __builtin__.True<br>except AttributeError:<br> True = 1<br></pre>
334 <h3> <a name="StatsAndExprs"></a>Statements and expressions</h3>
336 Control structures and expressions follow Python syntax for the most part.
337 When applied to Python objects, they have the same semantics as in Python
338 (unless otherwise noted). Most of the Python operators can also be applied
339 to C values, with the obvious semantics.
340 <p>If Python objects and C values are mixed in an expression, conversions
341 are performed automatically between Python objects and C numeric or string
345 <p>Reference counts are maintained automatically for all Python objects, and
346 all Python operations are automatically checked for errors, with appropriate
350 <h4> <a name="ExprSyntaxDifferences"></a>Differences between C and Cython
353 are some differences in syntax and semantics between C expressions and
354 Cython expressions, particularly in the area of C constructs which have
355 no direct equivalent in Python.<br>
358 <li>An integer literal without an <span style="font-family: monospace; font-weight: bold;">L</span> suffix is treated as a C constant, and will be truncated to whatever size your C compiler thinks appropriate. With an <span style="font-family: monospace; font-weight: bold;">L</span> suffix, it will be converted to Python long integer (even if it would be small enough to fit into a C int).<br>
361 <li> There is no <b><tt>-></tt></b> operator in Cython. Instead of <tt>p->x</tt>,
362 use <tt>p.x</tt></li>
364 <li> There is no <b><tt>*</tt></b> operator in Cython. Instead of
365 <tt>*p</tt>, use <tt>p[0]</tt></li>
367 <li> There is an <b><tt>&</tt></b> operator, with the same semantics
370 <li> The null C pointer is called <b><tt>NULL</tt></b>, not 0 (and
371 <tt>NULL</tt> is a reserved word).</li>
373 <li> Character literals are written with a <b>c</b> prefix, for
378 <li> Type casts are written <b><tt><type>value</tt></b> , for example:</li>
380 <pre>cdef char *p, float *q<br>p = <char*>q</pre>
382 <i><b>Warning</b>: Don't attempt to use a typecast to convert between
383 Python and C data types -- it won't do the right thing. Leave Cython to perform
384 the conversion automatically.</i>
388 <h4> <a name="ForFromLoop"></a>Integer for-loops</h4>
390 You should be aware that a for-loop such as
391 <blockquote><tt>for i in range(n):</tt> <br>
392 <tt> ...</tt></blockquote>
394 won't be very fast, even if <tt>i</tt> and <tt>n</tt> are declared as
395 C integers, because <tt>range</tt> is a Python function. For iterating over
396 ranges of integers, Cython has another form of for-loop:
397 <blockquote><tt>for i from 0 <= i < n:</tt> <br>
398 <tt> ...</tt></blockquote>
400 If the loop variable and the lower and upper bounds are all C integers,
401 this form of loop will be much faster, because Cython will translate it into
403 <p>Some things to note about the <tt>for-from</tt> loop: </p>
408 <li> The target expression must be a variable name.</li>
409 <li> The name between the lower and upper bounds must be the same as
410 the target name.</li>
411 <li> The direction of iteration is determined by the relations. If they
412 are both from the set {<tt><</tt>, <tt><=</tt>} then it is upwards;
413 if they are both from the set {<tt>></tt>, <tt>>=</tt>} then it is
414 downwards. (Any other combination is disallowed.)</li>
418 Like other Python looping statements, <tt>break</tt> and <tt>continue</tt> may be used in the body, and the loop may have an <tt>else</tt> clause.
420 <h2> <hr width="100%"></h2>
423 <h3> <a name="ExceptionValues"></a>Error return values</h3>
425 If you don't do anything special, a function declared with <b>cdef</b> that does not return a Python object has no way of reporting Python exceptions
426 to its caller. If an exception is detected in such a function, a warning
427 message is printed and the exception is ignored.
428 <p>If you want a C function that does not return a Python object to be able
429 to propagate exceptions to its caller, you need to declare an <b>exception
430 value</b> for it. Here is an example: </p>
433 <blockquote><tt>cdef int spam() except -1:</tt> <br>
434 <tt> ...</tt></blockquote>
436 With this declaration, whenever an exception occurs inside <tt>spam</tt>,
437 it will immediately return with the value <tt>-1</tt>. Furthermore, whenever
438 a call to <tt>spam</tt> returns <tt>-1</tt>, an exception will be assumed
439 to have occurred and will be propagated.
440 <p>When you declare an exception value for a function, you should never explicitly
441 return that value. If all possible return values are legal and you can't
442 reserve one entirely for signalling errors, you can use an alternative form
443 of exception value declaration: </p>
446 <blockquote><tt>cdef int spam() except? -1:</tt> <br>
447 <tt> ...</tt></blockquote>
449 The "?" indicates that the value <tt>-1</tt> only indicates a <i>possible</i> error. In this case, Cython generates a call to <tt>PyErr_Occurred</tt>if the
450 exception value is returned, to make sure it really is an error.
451 <p>There is also a third form of exception value declaration: </p>
454 <blockquote><tt>cdef int spam() except *:</tt> <br>
455 <tt> ...</tt></blockquote>
457 This form causes Cython to generate a call to <tt>PyErr_Occurred</tt> after
458 <i>every</i> call to spam, regardless of what value it returns. If you have
459 a function returning <tt>void</tt> that needs to propagate errors, you will
460 have to use this form, since there isn't any return value to test.
461 <p>Some things to note: </p>
466 <li> Currently, exception values can only declared for functions returning
467 an integer, float or pointer type, and the value must be a <i>literal</i>,
468 not an expression (although it can be negative). The only possible pointer
469 exception value is <tt>NULL</tt>. Void functions can only use the <tt>except
472 <li> The exception value specification is part of the signature
473 of the function. If you're passing a pointer to a function as a parameter
474 or assigning it to a variable, the declared type of the parameter or variable
475 must have the same exception value specification (or lack thereof). Here
476 is an example of a pointer-to-function declaration with an exception value:</li>
478 <pre><tt>int (*grail)(int, char *) except -1</tt></pre>
480 <li> You don't need to (and shouldn't) declare exception values for functions
481 which return Python objects. Remember that a function with no declared return
482 type implicitly returns a Python object.</li>
487 <h4> <a name="CheckingReturnValues"></a>Checking return values of non-Cython
490 It's important to understand that the <tt>except</tt> clause does <i>not</i> cause an error to be <i>raised</i> when the specified value is returned. For
491 example, you can't write something like
492 <blockquote> <pre>cdef extern FILE *fopen(char *filename, char *mode) except NULL <font color="#ed181e"># WRONG!</font></pre>
495 and expect an exception to be automatically raised if a call to fopen
496 returns NULL. The except clause doesn't work that way; its only purpose
497 is for <i>propagating</i> exceptions that have already been raised, either
498 by a Cython function or a C function that calls Python/C API routines. To
499 get an exception from a non-Python-aware function such as fopen, you will
500 have to check the return value and raise it yourself, for example,
501 <blockquote> <pre>cdef FILE *p<br>p = fopen("spam.txt", "r")<br>if p == NULL:<br> raise SpamError("Couldn't open the spam file")</pre>
505 <h4> <hr width="100%"></h4>
508 <h4> <a name="IncludeStatement"></a>The <tt>include</tt> statement</h4>
510 For convenience, a large Cython module can be split up into a number of
511 files which are put together using the <b>include</b> statement, for example
513 <blockquote> <pre>include "spamstuff.pxi"</pre>
516 The contents of the named file are textually included at that point. The
517 included file can contain any complete top-level Cython statements, including
518 other <b>include</b> statements. The <b>include</b> statement itself can
519 only appear at the top level of a file.
520 <p>The <b>include</b> statement can also be used in conjunction with <a href="#PublicDecls"><b>public</b> declarations</a> to make C functions and
521 variables defined in one Cython module accessible to another. However, note
522 that some of these uses have been superseded by the facilities described
523 in <a href="sharing.html">Sharing Declarations Between Cython Modules</a>,
524 and it is expected that use of the <b>include</b> statement for this purpose
525 will be phased out altogether in future versions. </p>
528 <h2> <hr width="100%"><a name="InterfacingWithExternal"></a>Interfacing with External
530 <hr width="100%"></h2>
532 One of the main uses of Cython is wrapping existing libraries of C code.
533 This is achieved by using <a href="#ExternDecls">external declarations</a> to declare the C functions and variables from the library that you want to
535 <p>You can also use <a href="#PublicDecls">public declarations</a> to make
536 C functions and variables defined in a Cython module available to external
537 C code. The need for this is expected to be less frequent, but you might
538 want to do it, for example, if you are embedding Python in another application
539 as a scripting language. Just as a Cython module can be used as a bridge to
540 allow Python code to call C code, it can also be used to allow C code to
541 call Python code. </p>
544 <h3> <a name="ExternDecls"></a>External declarations</h3>
546 By default, C functions and variables declared at the module level are
547 local to the module (i.e. they have the C <b>static</b> storage class). They
548 can also be declared <b>extern</b> to specify that they are defined elsewhere,
550 <blockquote> <pre>cdef extern int spam_counter</pre>
551 <pre>cdef extern void order_spam(int tons)</pre>
555 <blockquote> </blockquote>
558 <h4> <a name="ReferencingHeaders"></a>Referencing C header files</h4>
560 When you use an extern definition on its own as in the examples above,
561 Cython includes a declaration for it in the generated C file. This can cause
562 problems if the declaration doesn't exactly match the declaration that will
563 be seen by other C code. If you're wrapping an existing C library, for example,
564 it's important that the generated C code is compiled with exactly the same
565 declarations as the rest of the library.
566 <p>To achieve this, you can tell Cython that the declarations are to be found
567 in a C header file, like this: </p>
570 <blockquote> <pre>cdef extern from "spam.h":</pre>
571 <pre> int spam_counter</pre>
572 <pre> void order_spam(int tons)</pre>
575 The <b>cdef extern from</b> clause does three things:
578 <li> It directs Cython to place a <b>#include</b> statement for the named
579 header file in the generated C code.<br>
581 <li> It prevents Cython from generating any C code for the declarations
582 found in the associated block.<br>
584 <li> It treats all declarations within the block as though they
585 started with <b>cdef extern</b>.</li>
589 It's important to understand that Cython does <i>not</i> itself read the
590 C header file, so you still need to provide Cython versions of any declarations
591 from it that you use. However, the Cython declarations don't always have to
592 exactly match the C ones, and in some cases they shouldn't or can't. In particular:
596 <li> Don't use <b>const</b>. Cython doesn't know anything about const,
597 so just leave it out. Most of the time this shouldn't cause any problem,
598 although on rare occasions you might have to use a cast.<sup><a href="#Footnote1"> 1</a></sup><br>
600 <li> Leave out any platform-specific extensions to C declarations
601 such as <b>__declspec()</b>.<br>
603 <li> If the header file declares a big struct and you only want
604 to use a few members, you only need to declare the members you're interested
605 in. Leaving the rest out doesn't do any harm, because the C compiler will
606 use the full definition from the header file.<br>
608 In some cases, you might not need <i>any</i> of the struct's members, in
609 which case you can just put <tt>pass</tt> in the body of the struct declaration,
612 <tt> cdef extern from "foo.h":<br>
613 struct spam:<br>
614 pass</tt><br>
616 Note that you can only do this inside a <b>cdef extern from</b> block; struct
617 declarations anywhere else must be non-empty.<br>
620 <li> If the header file uses typedef names such as <b>size_t </b>to refer
621 to platform-dependent flavours of numeric types, you will need a corresponding
622 <b>ctypedef</b> statement, but you don't need to match the type exactly,
623 just use something of the right general kind (int, float, etc). For example,</li>
625 <pre>ctypedef int size_t</pre>
627 will work okay whatever the actual size of a size_t is (provided the header
628 file defines it correctly). <br>
629 <li> If the header file uses macros to define constants, translate
630 them into a dummy <b>enum</b> declaration.<br>
632 <li> If the header file defines a function using a macro, declare
633 it as though it were an ordinary function, with appropriate argument and
638 A few more tricks and tips:
641 <li> If you want to include a C header because it's needed by another
642 header, but don't want to use any declarations from it, put <tt><font size="+1">pass</font></tt> in the extern-from block:</li>
650 <tt>cdef extern from "spam.h":</tt> <br>
651 <tt> pass</tt> </ul>
658 <li> If you want to include some external declarations, but don't want
659 to specify a header file (because it's included by some other header that
660 you've already included) you can put <tt>*</tt> in place of the header file
666 <blockquote> <blockquote><tt>cdef extern from *:</tt> <br>
667 <tt> ...</tt></blockquote>
671 <h4> <a name="StructDeclStyles"></a>Styles of struct, union and enum declaration</h4>
673 There are two main ways that structs, unions and enums can be declared
674 in C header files: using a tag name, or using a typedef. There are also some
675 variations based on various combinations of these.
676 <p>It's important to make the Cython declarations match the style used in the
677 header file, so that Cython can emit the right sort of references to the type
678 in the code it generates. To make this possible, Cython provides two different
679 syntaxes for declaring a struct, union or enum type. The style introduced
680 above corresponds to the use of a tag name. To get the other style, you prefix
681 the declaration with <b>ctypedef</b>, as illustrated below. </p>
684 <p>The following table shows the various possible styles that can be found
685 in a header file, and the corresponding Cython declaration that you should
686 put in the <b>cdef exern from </b>block. Struct declarations are used as
687 an example; the same applies equally to union and enum declarations. </p>
690 <p>Note that in all the cases below, you refer to the type in Cython code simply
691 as <tt><font size="+1">Foo</font></tt>, not <tt><font size="+1">struct Foo</font></tt>.
693 <table cellpadding="5">
695 <tr bgcolor="#8cbc1c" valign="top">
696 <td bgcolor="#8cbc1c"> </td>
697 <td bgcolor="#ff9933" nowrap="nowrap"><b>C code</b></td>
698 <td bgcolor="#66cccc" valign="top"><b>Possibilities for corresponding
700 <td bgcolor="#99cc33" valign="top"><b>Comments</b></td>
702 <tr bgcolor="#8cbc1c" valign="top">
704 <td bgcolor="#ff9900"><tt>struct Foo {</tt> <br>
705 <tt> ...</tt> <br>
707 <td bgcolor="#66cccc"><tt>cdef struct Foo:</tt> <br>
708 <tt> ...</tt></td>
709 <td>Cython will refer to the type as <tt>struct Foo </tt>in the generated
710 C code<tt>.</tt></td>
712 <tr bgcolor="#8cbc1c" valign="top">
713 <td valign="top">2</td>
714 <td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct {</tt> <br>
715 <tt> ...</tt> <br>
717 <td bgcolor="#66cccc" valign="top"><tt>ctypedef struct Foo:</tt> <br>
718 <tt> ...</tt></td>
719 <td valign="top">Cython will refer to the type simply as <tt>Foo</tt>
720 in the generated C code.</td>
722 <tr bgcolor="#8cbc1c" valign="top">
723 <td rowspan="2">3</td>
724 <td rowspan="2" bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct
726 <tt> ...</tt> <br>
728 <td bgcolor="#66cccc" nowrap="nowrap" valign="top"><tt>cdef struct foo:</tt> <br>
729 <tt> ...</tt> <br>
730 <tt>ctypedef foo Foo #optional</tt></td>
731 <td rowspan="2" valign="top">If the C header uses both a tag and a typedef
732 with <i>different</i> names, you can use either form of declaration in Cython
733 (although if you need to forward reference the type, you'll have to use
734 the first form).</td>
737 <td bgcolor="#66cccc"><tt>ctypedef struct Foo:</tt> <br>
738 <tt> ...</tt></td>
740 <tr bgcolor="#8cbc1c" valign="top">
742 <td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct Foo {</tt> <br>
743 <tt> ...</tt> <br>
745 <td bgcolor="#66cccc" valign="top"><tt>cdef struct Foo:</tt> <br>
746 <tt> ...</tt></td>
747 <td>If the header uses the <i>same</i> name for the tag and the typedef,
748 you won't be able to include a <b>ctypedef</b> for it -- but then, it's not
755 <h4> <a name="AccessingAPI"></a>Accessing Python/C API routines</h4>
757 One particular use of the <b>cdef extern from</b> statement is for gaining
758 access to routines in the Python/C API. For example,
759 <blockquote> <pre>cdef extern from "Python.h":</pre>
760 <pre> object PyString_FromStringAndSize(char *s, int len)</pre>
763 will allow you to create Python strings containing null bytes.
768 <h3> <a name="CNameSpecs"></a>Resolving naming conflicts - C name specifications</h3>
770 Each Cython module has a single module-level namespace for both Python
771 and C names. This can be inconvenient if you want to wrap some external
772 C functions and provide the Python user with Python functions of the same
774 <p>Cython 0.8 provides a couple of different ways of solving this problem.
775 The best way, especially if you have many C functions to wrap, is probably
776 to put the extern C function declarations into a different namespace using
777 the facilities described in the section on <a href="sharing.html">sharing
778 declarations between Cython modules</a>. </p>
781 <p>The other way is to use a <b>c name specification</b> to give different
782 Cython and C names to the C function. Suppose, for example, that you want
783 to wrap an external function called <tt>eject_tomato</tt>. If you declare
787 <blockquote> <pre>cdef extern void c_eject_tomato "eject_tomato" (float speed)</pre>
790 then its name inside the Cython module will be <tt>c_eject_tomato</tt>,
791 whereas its name in C will be <tt>eject_tomato</tt>. You can then wrap it
793 <blockquote> <pre>def eject_tomato(speed):<br> c_eject_tomato(speed)</pre>
796 so that users of your module can refer to it as <tt>eject_tomato</tt>.
798 <p>Another use for this feature is referring to external names that happen
799 to be Cython keywords. For example, if you want to call an external function
800 called <tt>print</tt>, you can rename it to something else in your Cython
804 <p>As well as functions, C names can be specified for variables, structs,
805 unions, enums, struct and union members, and enum values. For example, </p>
808 <blockquote> <pre>cdef extern int one "ein", two "zwei"<br>cdef extern float three "drei"<br><br>cdef struct spam "SPAM":<br> int i "eye"</pre>
809 <tt>cdef enum surprise "inquisition":</tt> <br>
810 <tt> first "alpha"</tt> <br>
811 <tt> second "beta" = 3</tt></blockquote>
815 <h3> <a name="PublicDecls"></a>Public Declarations</h3>
817 You can make C variables and functions defined in a Cython module accessible
818 to external C code (or another Cython module) using the <b><tt>public</tt></b> keyword, as follows:
819 <blockquote><tt>cdef public int spam # public variable declaration</tt> <p><tt>cdef public void grail(int num_nuns): # public function declaration</tt> <br>
820 <tt> ...</tt></p>
823 If there are any <tt>public</tt> declarations in a Cython module, a <b>.h</b> file is generated containing equivalent C declarations for inclusion in other
825 <p>Cython also generates a <b>.pxi</b> file containing Cython versions of the
826 declarations for inclusion in another Cython module using the <b><a href="#IncludeStatement">include</a></b> statement. If you use this, you
827 will need to arrange for the module using the declarations to be linked
828 against the module defining them, and for both modules to be available to
829 the dynamic linker at run time. I haven't tested this, so I can't say how
830 well it will work on the various platforms. </p>
833 <blockquote>NOTE: If all you want to export is an extension type, there is
834 now a better way -- see <a href="sharing.html">Sharing Declarations Between
835 Cython Modules</a>.</blockquote>
838 <h2> <hr width="100%">Extension Types
839 <hr width="100%"></h2>
841 One of the most powerful features of Cython is the ability to easily create
842 new built-in Python types, called <b>extension types</b>. This is a major
843 topic in itself, so there is a <a href="extension_types.html">separate
844 page</a> devoted to it.
845 <h2> <hr width="100%">Sharing Declarations Between Cython Modules
846 <hr width="100%"></h2>
848 Cython 0.8 introduces a substantial new set of facilities allowing a Cython
849 module to easily import and use C declarations and extension types from another
850 Cython module. You can now create a set of co-operating Cython modules just
851 as easily as you can create a set of co-operating Python modules. There is
852 a <a href="sharing.html">separate page</a> devoted to this topic.
853 <h2> <hr width="100%"><a name="Limitations"></a>Limitations
854 <hr width="100%"></h2>
857 <h3> <a name="Unsupported"></a>Unsupported Python features</h3>
859 Cython is not quite a full superset of Python. The following restrictions
861 <blockquote> <li> Function definitions (whether using <b>def</b> or <b>cdef</b>)
862 cannot be nested within other function definitions.<br>
864 <li> Class definitions can only appear at the top level of a module,
865 not inside a function.<br>
867 <li> The<tt> import *</tt> form of import is not allowed anywhere
868 (other forms of the import statement are fine, though).<br>
870 <li> Generators cannot be defined in Cython.<br>
873 <li> The <tt>globals()</tt> and <tt>locals()</tt> functions cannot be
877 The above restrictions will most likely remain, since removing them would
878 be difficult and they're not really needed for Cython's intended applications.
880 <p>There are also some temporary limitations, which may eventually be lifted, including:
884 <blockquote> <li> Class and function definitions cannot be placed inside
885 control structures.<br>
887 <li> In-place arithmetic operators (+=, etc) are not yet supported.<br>
889 <li> List comprehensions are not yet supported.<br>
891 <li> There is no support for Unicode.<br>
893 <li> Special methods of extension types cannot have functioning
897 <li> The use of string literals as comments is not recommended at present,
898 because Cython doesn't optimize them away, and won't even accept them in
899 places where executable statements are not allowed.</li>
902 <h3> <a name="SemanticDifferences"></a>Semantic differences between Python
906 <h4> Behaviour of class scopes</h4>
908 In Python, referring to a method of a class inside the class definition,
909 i.e. while the class is being defined, yields a plain function object, but
910 in Cython it yields an unbound method<sup><font size="-2"><a href="#Footnote2">2</a></font></sup>. A consequence of this is that the
911 usual idiom for using the classmethod and staticmethod functions, e.g.
912 <blockquote> <pre>class Spam:</pre>
913 <pre> def method(cls):<br> ...</pre>
914 <pre> method = classmethod(method)</pre>
917 will not work in Cython. This can be worked around by defining the function
918 <i>outside</i> the class, and then assigning the result of classmethod or
919 staticmethod inside the class, i.e.
920 <blockquote> <pre>def Spam_method(cls):<br> ...</pre>
921 <pre>class Spam:</pre>
922 <pre> method = classmethod(Spam_method)</pre>
926 <h1> <hr width="100%"><font size="+0">Footnotes</font> <hr width="100%"></h1>
928 <a name="Footnote1"></a>1. A problem with const could arise if you have
930 <blockquote> <pre>cdef extern from "grail.h":<br> char *nun</pre>
933 where grail.h actually contains
934 <blockquote> <pre>extern const char *nun;</pre>
938 <blockquote> <pre>cdef void languissement(char *s):<br> #something that doesn't change s</pre>
940 <pre>languissement(nun)</pre>
943 which will cause the C compiler to complain. You can work around it by
944 casting away the constness:
945 <blockquote> <pre>languissement(<char *>nun)</pre>
949 <hr width="100%"><a name="Footnote2"></a>2. The reason for the different behaviour
950 of class scopes is that Cython-defined Python functions are PyCFunction objects,
951 not PyFunction objects, and are not recognised by the machinery that creates
952 a bound or unbound method when a function is extracted from a class. To get
953 around this, Cython wraps each method in an unbound method object itself before
954 storing it in the class's dictionary. <br>