Is Python Interpreted or Compiled? Understanding Python Execution

compilerefficiencyinterpretersprogramming-languagespython

This is just a wondering I had while reading about interpreted and compiled languages.

Ruby is no doubt an interpreted language since the source code is processed by an interpreter at the point of execution.
On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution.

Now coming to Python:

  • A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly.
  • When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior.

These suggest that a python code is compiled every time it is imported in a new process to create a .pyc while it is interpreted when directly executed.

So which type of language should I consider it as? Interpreted or Compiled?
And how does its efficiency compare to interpreted and compiled languages?

According to wiki's Interpreted Languages page, it is listed as a language compiled to Virtual Machine Code, what is meant by that?

Best Answer

It's worth noting that languages are not interpreted or compiled, but rather language implementations either interpret or compile code. You noted that Ruby is an "interpreted language", but you can compile Ruby à la MacRuby, so it's not always an interpreted language.

Pretty much every Python implementation consists of an interpreter (rather than a compiler). The .pyc files you see are byte code for the Python virtual machine (similar to Java's .class files). They are not the same as the machine code generated by a C compiler for a native machine architecture. Some Python implementations, however, do consist of a just-in-time compiler that will compile Python byte code into native machine code.

(I say "pretty much every" because I don't know of any native machine compilers for Python, but I don't want to claim that none exist anywhere.)