Why is it impossible to create a compiler than can compile Python to machinecode like C?

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Mar 5 01:27:52 CET 2013


On Mar 4, 2013 3:02 PM, "CM" <cmpython at gmail.com> wrote:
>
>
> > The main issue is that python has dynamic typing.  The type of object
> > that is referenced by a particular name can vary, and there's no way
> > (in general) to know at compile time what the type of object "foo" is.
> >
> > That makes generating object code to manipulate "foo" very difficult.
>
> Could you help me understand this better?  For example, if you
> have this line in the Python program:
>
> foo = 'some text'
> bar = {'apple':'fruit'}
>
> If the interpreter can determine at runtime that foo is a string
> and bar is a dict, why can't the compiler figure that out at
> compile time?  Or is the problem that if later in the program
> you have this line:
>
> foo = 12
>
> now foo is referring to an integer object, not a string, and
> compilers can't have two names referring to two different
> types of objects?  Something like that?
>
> I in no way doubt you that this is not possible, I just don't
> understand enough about how compiling works to yet "get"
> why dynamic typing is a problem for compilers.
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list

In the case of literals, the compiler can figure out type information (and
I believe it does do some constant folding). But as soon as you let
something else get in between you and the constant, you lose all guarantees.

import random

if random.random() <0.5 :
    spam = 3
else:
    spam = "hello world"

Then you get into monkey patching and dealing with types that may not be
defined at compile time. The only way a python compiler could convert that
to x86 assembly is if generated code that would look up the type
information at runtime. You'd basically be outputting a python interpreter.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130304/38423404/attachment.html>


More information about the Python-list mailing list