Python – Why does Python need both a compiler and an interpreter

bytecodecompilerpython

I can understand the fact that Java needs both a compiler and an interpreter. It compiles source code to bytecode and then a virtual machine (on Windows, on Linux, on Android, etc.) translates that bytecode to machine code for the current architecture.

But why does Python need both a compiler and an interpreter? Since Python is not platform independent, why not just use interpretation? As far as I know, you cannot execute a Python program (compiled to bytecode) on any Windows or Linux machine without modification. Or am I wrong?

Best Answer

As far as I know, you cannot execute a Python program (compiled to bytecode) on every machine, such as on windows, or on linux without modification.

You are incorrect. The python bytecode is cross platform. See Is python bytecode version-dependent? Is it platform-dependent? on Stack Overflow. However, it is not compatible across versions. Python 2.6 cannot execute Python 2.5 files. So while cross-platform, its not generally useful as a distribution format.

But why Python needs both a compiler and an interpreter?

Speed. Strict interpretation is slow. Virtually every "interpreted" language actually compiles the source code into some sort of internal representation so that it doesn't have to repeatedly parse the code. In python's case it saves this internal representation to disk so that it can skip the parsing/compiling process next time it needs the code.