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

Grant Edwards invalid at invalid.invalid
Mon Mar 4 11:36:36 EST 2013


On 2013-02-28, kramer65 <kramerh at gmail.com> wrote:

> I'm using Python for a while now and I love it. There is just one
> thing I cannot understand. There are compilers for languages like C
> and C++. why is it impossible to create a compiler that can compile
> Python code to machinecode?

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.


> My reasoning is as follows: When GCC compiles a program written in
> C++, it simply takes that code and decides what instructions that
> would mean for the computer's hardware. What does the CPU need to do,
> what does the memory need to remember, etc. etc. If you can create
> this machinecode from C++, then I would suspect that it should also
> be possible to do this (without a C-step in between) for programs
> written in Python.
>
> Where is my reasoning wrong here? Is that because Python is
> dynamically typed?

Yes.

> Does machinecode always need to know whether a
> variable is an int or a float?

Yes. Not only might it be an int or a float, it might be a string, a
list, a dictionary, a network socket, a file, or some user-defined
object type that the compiler has no way of knowing about.

> And if so, can't you build a compiler which creates machinecode that
> can handle both ints and floats in case of doubt?

That's pretty much what you've got now.  The Python compiler compiles
the source code as much as it can, and the VM is the "machinecode that
can handle both ints and floats".

> Or is it actually possible to do, but so much work that nobody does
> it?
>
> I googled around, and I *think* it is because of the dynamic typing,
> but I really don't understand why this would be an issue..

Can you explain how to generate machine code to handle any possible
object type than any Python user might ever create?

-- 
Grant Edwards               grant.b.edwards        Yow! for ARTIFICIAL
                                  at               FLAVORING!!
                              gmail.com            



More information about the Python-list mailing list