300

From my understanding:

An interpreted language is a high-level language run and executed by an interpreter (a program which converts the high-level language to machine code and then executing) on the go; it processes the program a little at a time.

A compiled language is a high-level language whose code is first converted to machine-code by a compiler (a program which converts the high-level language to machine code) and then executed by an executor (another program for running the code).

Correct me if my definitions are wrong.

Now coming back to Python, I am bit confused about this. Everywhere you learn that Python is an interpreted language, but it's interpreted to some intermediate code (like byte-code or IL) and not to the machine code. So which program then executes the IM code? Please help me understand how a Python script is handled and run.

7
  • 3
    possible duplicate of Is Python interpreted (like Javascript or PHP)?
    – miku
    Jul 31, 2011 at 13:36
  • 2
    Python does create .pyc files (so-called byecode) whenever a library is imported. AFAIK the bytecode can only speed up load times, not execution times. Jul 31, 2011 at 13:42
  • 2
    @aitchnyu: Caching the bytecode in .pyc files only speeds up loading indeed, but only becase the Python code is compiled to bytecode before execution anyway. Although I don't think it has been tried with Python specifically, other language implementations show that bytecode is indeed easier to interpret efficiently than a plain AST or, even worse, unparsed source code. Older Ruby versions interpreted from AST, for instance, and was AFAIK outperformed quite a bit by newer versions which compile to bytecode.
    – user395760
    Jul 31, 2011 at 13:48
  • Dont want to sound rude, but isnt that what I meant (but not as informed as you)? Jul 31, 2011 at 13:59
  • 1
    @aitchnyu: I don't know what you meant. I only know that your comment wasn't incorrect but provided good oppoturnity for some background info why it only speeds up load time, so I decided to add that information. No offense meant or taken :)
    – user395760
    Jul 31, 2011 at 14:01

16 Answers 16

365

First off, interpreted/compiled is not a property of the language but a property of the implementation. For most languages, most if not all implementations fall in one category, so one might save a few words saying the language is interpreted/compiled too, but it's still an important distinction, both because it aids understanding and because there are quite a few languages with usable implementations of both kinds (mostly in the realm of functional languages, see Haskell and ML). In addition, there are C interpreters and projects that attempt to compile a subset of Python to C or C++ code (and subsequently to machine code).

Second, compilation is not restricted to ahead-of-time compilation to native machine code. A compiler is, more generally, a program that converts a program in one programming language into a program in another programming language (arguably, you can even have a compiler with the same input and output language if significant transformations are applied). And JIT compilers compile to native machine code at runtime, which can give speed very close to or even better than ahead of time compilation (depending on the benchmark and the quality of the implementations compared).

But to stop nitpicking and answer the question you meant to ask: Practically (read: using a somewhat popular and mature implementation), Python is compiled. Not compiled to machine code ahead of time (i.e. "compiled" by the restricted and wrong, but alas common definition), "only" compiled to bytecode, but it's still compilation with at least some of the benefits. For example, the statement a = b.c() is compiled to a byte stream which, when "disassembled", looks somewhat like load 0 (b); load_str 'c'; get_attr; call_function 0; store 1 (a). This is a simplification, it's actually less readable and a bit more low-level - you can experiment with the standard library dis module and see what the real deal looks like. Interpreting this is faster than interpreting from a higher-level representation.

That bytecode is either interpreted (note that there's a difference, both in theory and in practical performance, between interpreting directly and first compiling to some intermediate representation and interpret that), as with the reference implementation (CPython), or both interpreted and compiled to optimized machine code at runtime, as with PyPy.

12
  • 3
    Alright, this means that a python script is first compiled to bytecode and then it is implemented by an interpreter like CPython, Jython or IronPython etc. Jul 31, 2011 at 13:54
  • 45
    No, it is compiled to bytecode and then the bytecode is executed by the respective VM. CPython is both the compiler and the VM, but Jython and IronPython are just the compiler. Jul 31, 2011 at 13:57
  • 1
    @Igacio: I don't have much experience with IronPython/Jython, but doesn't at least Jython provide an interpreter-like layer? I don't believe it's feasible to try turn Python into the statically-typed JVM bytecode. Still, good point about compiler and interpreter being part of the same package.
    – user395760
    Jul 31, 2011 at 14:00
  • 2
    @delnan: Well, Jython does act as a sort of intermediary between the Python language and the Java VM, but it does compile to Java bytecode. Jul 31, 2011 at 14:12
  • 1
    "...First off, interpreted/compiled is not a property of the language but a property of the implementation...". I do not think it is correct. And interpreted language can execute dynamic statements i.e. the source code is not known at the time of the program writing or even at the time of the application start. That's not an implementation detail but the design of the language. Jan 17, 2020 at 16:38
66

The CPU can only understand machine code indeed. For interpreted programs, the ultimate goal of an interpreter is to "interpret" the program code into machine code. However, usually a modern interpreted language does not interpret human code directly because it is too inefficient.

The Python interpreter first reads the human code and optimizes it to some intermediate code before interpreting it into machine code. That's why you always need another program to run a Python script, unlike in C++ where you can run the compiled executable of your code directly. For example, c:\Python27\python.exe or /usr/bin/python.

3
  • 28
    I like the point about "needing another program to run [it]". That helped clarify some of my thoughts.
    – Matt
    Oct 16, 2013 at 23:12
  • 2
    so python.exe first optimises the code and then interprets it? Mar 16, 2015 at 7:54
  • 4
    @KorayTugay, when python.exe is given human readable text source code, it first produces optimized byte code, then interprets that (as you say); however, when there is already a byte code file (pre-compiled), it doesn't have to do the first step, which saves some time. May 14, 2016 at 0:40
50

The answer depends on what implementation of python is being used. If you are using lets say CPython (The Standard implementation of python) or Jython (Targeted for integration with java programming language)it is first translated into bytecode, and depending on the implementation of python you are using, this bycode is directed to the corresponding virtual machine for interpretation. PVM (Python Virtual Machine) for CPython and JVM (Java Virtual Machine) for Jython.

But lets say you are using PyPy which is another standard CPython implementation. It would use a Just-In-Time Compiler.

1
  • 10
    Pypy is a Python implementation, not a "CPython" implementation. In fact, Pypy is an alternative to CPython (pypy.org/features.html).
    – Giorgio
    May 4, 2020 at 7:41
34

Yes, it is both compiled and interpreted language. Then why we generally call it as interpreted language?

see how it is both- compiled and interpreted?

First of all I want to tell that you will like my answer more if you are from the Java world.

In the Java the source code first gets converted to the byte code through javac compiler then directed to the JVM(responsible for generating the native code for execution purpose). Now I want to show you that we call the Java as compiled language because we can see that it really compiles the source code and gives the .class file(nothing but bytecode) through:

javac Hello.java -------> produces Hello.class file

java Hello -------->Directing bytecode to JVM for execution purpose

The same thing happens with python i.e. first the source code gets converted to the bytecode through the compiler then directed to the PVM(responsible for generating the native code for execution purpose). Now I want to show you that we usually call the Python as an interpreted language because the compilation happens behind the scene and when we run the python code through:

python Hello.py -------> directly excutes the code and we can see the output provied that code is syntactically correct

@ python Hello.py it looks like it directly executes but really it first generates the bytecode that is interpreted by the interpreter to produce the native code for the execution purpose.

CPython- Takes the responsibility of both compilation and interpretation.

Look into the below lines if you need more detail:

As I mentioned that CPython compiles the source code but actual compilation happens with the help of cython then interpretation happens with the help of CPython

Now let's talk a little bit about the role of Just-In-Time compiler in Java and Python

In JVM the Java Interpreter exists which interprets the bytecode line by line to get the native machine code for execution purpose but when Java bytecode is executed by an interpreter, the execution will always be slower. So what is the solution? the solution is Just-In-Time compiler which produces the native code which can be executed much more quickly than that could be interpreted. Some JVM vendors use Java Interpreter and some use Just-In-Time compiler. Reference: click here

In python to get around the interpreter to achieve the fast execution use another python implementation(PyPy) instead of CPython. click here for other implementation of python including PyPy.

33

According to the official Python site, it's interpreted.

https://www.python.org/doc/essays/blurb/

Python is an interpreted, object-oriented, high-level programming language...

...

Since there is no compilation step ...

...

The Python interpreter and the extensive standard library are available...

...

Instead, when the interpreter discovers an error, it raises an exception. When the program doesn't catch the exception, the interpreter prints a stack trace.

26

Its a big confusion for people who just started working in python and the answers here are a little difficult to comprehend so i'll make it easier.

When we instruct Python to run our script, there are a few steps that Python carries out before our code actually starts crunching away:

  • It is compiled to bytecode.
  • Then it is routed to virtual machine.

When we execute some source code, Python compiles it into byte code. Compilation is a translation step, and the byte code is a low-level platform-independent representation of source code.

Note that the Python byte code is not binary machine code (e.g., instructions for an Intel chip).

Actually, Python translate each statement of the source code into byte code instructions by decomposing them into individual steps. The byte code translation is performed to speed execution. Byte code can be run much more quickly than the original source code statements. It has.pyc extension and it will be written if it can write to our machine.

So, next time we run the same program, Python will load the .pyc file and skip the compilation step unless it's been changed. Python automatically checks the timestamps of source and byte code files to know when it must recompile. If we resave the source code, byte code is automatically created again the next time the program is run.

If Python cannot write the byte code files to our machine, our program still works. The byte code is generated in memory and simply discarded on program exit. But because .pyc files speed startup time, we may want to make sure it has been written for larger programs.

Let's summarize what happens behind the scenes. When Python executes a program, Python reads the .py into memory, and parses it in order to get a bytecode, then goes on to execute. For each module that is imported by the program, Python first checks to see whether there is a precompiled bytecode version, in a .pyo or .pyc, that has a timestamp which corresponds to its .py file. Python uses the bytecode version if any. Otherwise, it parses the module's .py file, saves it into a .pyc file, and uses the bytecode it just created.

Byte code files are also one way of shipping Python codes. Python will still run a program if all it can find are.pyc files, even if the original .py source files are not there.

Python Virtual Machine (PVM)

Once our program has been compiled into byte code, it is shipped off for execution to Python Virtual Machine (PVM). The PVM is not a separate program. It need not be installed by itself. Actually, the PVM is just a big loop that iterates through our byte code instruction, one by one, to carry out their operations. The PVM is the runtime engine of Python. It's always present as part of the Python system. It's the component that truly runs our scripts. Technically it's just the last step of what is called the Python interpreter.

1
  • I think the important part that you need to emphasize is that Python, like PHP, JSP & CFML, gets compiled at runtime. It is not pre compiled like Java or C# This allows a Dev to make changes and just upload the changes to the server, and that’s it. We don’t need to build anything, manually, after we have made the changes. Jul 10, 2023 at 8:09
7

If ( You know Java ) {

Python code is converted into bytecode like java does.
That bytecode is executed again everytime you try to access it.

} else {

Python code is initially traslated into something called bytecode
that is quite close to machine language but not actual machine code
so each time we access or run it that bytecode is executed again

}

1
  • Well. Everything is eventually converted into byte code. The important part, which differentiates languages, is when this process occurs. With Python, like PHP, JSP & CFML, the process happens just before runtime. It is carried out by the application server. Languages like Java & C# require the Dev to manually “build” the application after each set of changes. The build process, precompiles the code into byte code. This is meant to run quicker, but in my experience this is a myth. Jul 10, 2023 at 8:14
5

It really depends on the implementation of the language being used! There is a common step in any implementation, though: your code is first compiled (translated) to intermediate code - something between your code and machine (binary) code - called bytecode (stored into .pyc files). Note that this is a one-time step that will not be repeated unless you modify your code.

And that bytecode is executed every time you are running the program. How? Well, when we run the program, this bytecode (inside a .pyc file) is passed as input to a Virtual Machine (VM)1 - the runtime engine allowing our programs to be executed - that executes it.

Depending on the language implementation, the VM will either interpret the bytecode (in the case of CPython2 implementation) or JIT-compile3 it (in the case of PyPy4 implementation).

Notes:

1 an emulation of a computer system

2 a bytecode interpreter; the reference implementation of the language, written in C and Python - most widely used

3 compilation that is being done during the execution of a program (at runtime)

4 a bytecode JIT compiler; an alternative implementation to CPython, written in RPython (Restricted Python) - often runs faster than CPython

3

For newbies

Python automatically compiles your script to compiled code, so called byte code, before running it.

Running a script is not considered an import and no .pyc will be created.

For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.

2

Almost, we can say Python is interpreted language. But we are using some part of one time compilation process in python to convert complete source code into byte-code like java language.

1

The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.

Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).

Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.

1

Python(the interpreter) is compiled.

Proof: It won't even compile your code if it contains syntax error.

Example 1:

print("This should print") 
a = 9/0 

Output:

This should print
Traceback (most recent call last):
  File "p.py", line 2, in <module>
    a = 9/0
ZeroDivisionError: integer division or modulo by zero

Code gets compiled successfully. First line gets executed (print) second line throws ZeroDivisionError (run time error) .

Example 2:

print("This should not print")
/0         

Output:

  File "p.py", line 2
    /0
    ^
SyntaxError: invalid syntax

Conclusion: If your code file contains SyntaxError nothing will execute as compilation fails.

1
  • 1
    If you try print("this should print"); a=9/0; then you will get the real answer. Jul 25, 2021 at 15:02
1

As sone one already said, "interpreted/compiled is not a property of the language but a property of the implementation." Python can be used in interpretation mode as well as compilation mode. When you run python code directly from terminal or cmd then the python interpreter starts. Now if you write any command then this command will be directly interpreted. If you use a file containing Python code and running it in IDE or using a command prompt it will be compiled first the whole code will be converted to byte code and then it will run. So it depends on how we use it.

0

Seems to be a case of semantics. I think most of us infer that the usual result of compiling is machine-code. With that in mind I say to myself that python is not compiled. I would be wrong though because compile really means convert to a lower level so converting from source to byte-code is also compiling.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. Oct 13, 2021 at 6:21
0

Statement

Python is an interpreted language, that's no debate. Even if Python is 'compiling' the code into Bytecode, it is not a complete compilation procedure, and besides this, Python does not 'compile' all code (values and types) into bytecode. My analysis was ran against the following code:

Framework used to test the statement's correctness

import time
import dis
import main


def error():
    print("\n\n#############")
    print("##  ERROR  ##")
    print("#############\n")
    syntax_error  # <==== Syntax error
    syntax_error  # <==== Syntax error


def init():
    # GET THE INITIAL TIME
    t = time.time()

    while True:
        elapsed_time = time.time() - t
        if elapsed_time > 10:
            print("\n\nELAPSED TIME: " + str(int(elapsed_time)) + "\n\n")
            error()


if __name__ == "__main__":
    # PRINT THE GENERATED BYTECODE FOR THE CURRENT PROGRAM FILE
    print("\n\n##########################")
    print("##  GENERATED BYTECODE  ##")
    print("##########################\n")
    print(str(dis.dis(main)) + "\n\n")
    init()

The above shown code will print the generated byte code generated for the file, then it will get the initial time for the initiation of a loop. When the aforementioned loop is generated, it will check the elapsed time since the initial time was set and when the elapsed time is greater than 10 seconds, it will call a method that contains a syntactical error.

Result of the testing

enter image description here enter image description here

The generated bytecode for the code used to test the statement is shown above. In the above shown bytecode, the attributes contained with the bytecode are the constant names, method names, and method calls instructions, and simple return instructions. So the Lexer of the Python's bytecode 'compiler' is not checking the values and types of the variables.

enter image description here

As you can see in the above shown image, the compiler treated the non-existent variable syntax_error as a variable. A truly compiled language is performing type checks and value checks at compile time.

enter image description here

Also, the 'compilation' process itself as shown in the picture above, is creating references to some constants and it also creates some instructions regarding their allocation in memory as well as creating some references for method calls, rather than creating instructions regarding their allocation, creating naming references, precise memory allocation instructions, and precise operation instructions regarding the code execution within the methods.

enter image description here


enter image description here

For example, if we look at the print statement print("## ERROR ##") within the error() method within the generated bytecode, the instructions and references regarding the code are very simplistic. A reference to the print() method is created, then a reference to the string to be printed is created, and then an instruction regarding the fact that the print() method must be called is created.

enter image description here enter image description here

When the same action is performed in a JIT(Just In Time) language like C#, the result in the generated IL("Intermediary Language", C# version of the Bytecode) specify in which code language form the content of the method's body is represented with the reserved keywords cil managed, and it is specifying that the method name must be hidden because it overlapping with the method name of another method from a derived class using the reserved keyword hidebysig. The C# IL code is also specifying that inside the method the maximum amount of bits to be allocated on the stack is 8 by using the keyword and value .maxstack 8, it also specifying the points where no operation is performed by using the nop keyword, it is also specifying that for the string ## ERROR ## a string object must be created in the RAM memory in order to store the object by using the keyword ldstr, it is also specifying to call the method Console.WriteLine() by calling its assembly using the call keyword, and it also specifies when the method should return the control with the ret keyword. The C# code equivalent to the Python function was used as a direct comparison between a truly compiled language (C#) and one that it is not (Python). The difference in the amount of instructions, complexity, and their detail speaks for itself. In C# even the amount of memory to be allocated on the stack is specified in IL, while in the Python's bytecode not even method return instructions are specified for every method.



As a result of multiple mentioned facts mentioned above, when the Python program is running, after 10 seconds since the program started, the program will call the error() method which will in turn generate an error, rather than the error be caught up at compile time.

enter image description here

Conclusion

According with the results of the test case scenario based on the code provided, Python is not a truly compiled language. The bytecode translation procedure conducted by Python helps the interpreter execute the code faster because the code was lowered in a less resource consuming form of code from a processing point of view. This means that the interpreter has to put in less work converting the bytecode into assembly language, rather than converting the Python source code directly as assembly language CPU instructions. Another reason why Python is not a compiled language is because the compilation procedure takes place right before interpretation, rather than the compilation procedure taking place just once.

-3

In my opinion Python is put into an interpreter categoty because its designed to be capable of fully processing ( from python code to execution in cpu) individual python statement. I.e. you write one statement and you can execute it and if no errors then get the corresponding result.

Having an intermediate code (like bytecode) i believe doesnt make difference to categorize it overall as compiler. Though this component (intermediate code generation) is typically been part of compiler but it can also be used in interpreters. See wiki definition of interpreter https://en.m.wikipedia.org/wiki/Interpreter_(computing). Its a crucial piece to add efficiency in terms of execution speed. With cache its even more powerful so that if you havent changed code in current program scope you skip heavy processing steps like lexical, semantic analysis and even some of code optimization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.