[Python-ideas] A General Outline for Just-in-Time Acceleration of Python

Stefan Behnel stefan_ml at behnel.de
Mon Jun 16 09:05:25 CEST 2014


David Mertz, 14.06.2014 09:30:
> On Fri, Jun 13, 2014 at 11:54 PM, Joseph Martinot-Lagarde wrote:
> 
>> Cython compiles all python, it is not restricted.
> 
> Well, kinda yes and no.  You are correct of course, that anything that you
> can execute with 'python someprog' you can compile with 'cython someprog'.
>  However, there is an obvious sense in which adding an annotation (which
> is, of course, a syntax error for Python itself) "restricts" the code in
> Cython.  E.g.:
> 
>    def silly():
>         cdef int n, i

You can rewrite this as

     import cython

     @cython.locals(n=int, i=int)
     def silly():

which makes it valid Python but has the same semantics as your cdef
declaration when compiled in Cython.


>         for i in range(10):
>             if i < 5:
>                 n = i + 1
>             else:
>                 n = str(i)
> 
> This *silly* function isn't really Python code at all, of course.  But if
> you ignore the annotation, it would be--pointless code, but valid. As soon
> as you add the annotation, you *restrict* the type of code you can write in
> the scope of the annotation.

When compiled with Cython, you will get a TypeError on i == 5 (because you
said so), whereas it will run through the whole loop in Python.

Stefan




More information about the Python-ideas mailing list