Why not a Python compiler?

jack trades trades at none.com
Fri Feb 8 05:24:05 EST 2008


"Santiago Romero" <sromero at gmail.com> wrote in message
news:28eead2f-a40c-414b-bd3d-a941f8a851a2 at d70g2000hsb.googlegroups.com...
>  Why not a Python COMPILER?


Check out CLPython it has a Python compiler, though I highly doubt it is
what you are thinking of.


>From http://common-lisp.net/project/clpython/manual.html

Sometimes, the generated Python code can be simplified because the value of
an expressions is known at compile time. This is where compiler macros come
in. In this example, as 4 > 3 always holds, the compiler macro for py->
replaces (funcall #'py-> 4 3) by the Python value True. After that, the
compiler macro for py-val->lisp-bool recognizing True is a constant value,
replaces (py-val->lisp-bool True) by t. The Lisp compiler then deduces that
always the first branch of the if expression is taken, and replace the whole
(cond ...) by (py-print nil (list "y") nil).
In this example the compiler macros were able to remove a lot of the Lisp
code at compile time. This results in more efficient code. However, in
practice there is often not that much that can be decided at compile time,
due to Python-the-language being very dynamic. For example, in the
expression 5 + x the value of x can be anything. As classes are able to
redefine how the + operator behaves (by means of the __add__ and __radd__
methods), the value of 5 + x can be anything as well. Unless the context
gives more information about the type of x, the Lisp code must contain a
call to the generic addition function py-+.

Nevertheless, the compiler macro will inline "common" case, and make the
generic call only for "uncommon" arguments. If small integers (fixnums) are
common for the + operator, the compiler macro for py-+ could emit:

(if (typep x 'fixnum)
    (+ 5 x)
  (py-+ 5 x))The check for x being fixnum is very fast; and if x is indeed a
fixnum then the inline addition is also very fast. If x is not a fixnum, it
could another kind of (Lisp) number, or even a Pythonic object posing as a
number. The generic py-+ will handle that.


Compiled vs Interpreted Code
CLPython can run Python code in two modes, interpreted or compiled. In the
latter case, the Lisp code is translated into assembly. The advantage of
interpreted code is that debugging is easier (the stack trace contains more
information); on the other hand execution of compiled code is much faster.



Jack Trades





More information about the Python-list mailing list