edit

How is Python executed?

It is not absolutely necessary to know exactly how it works, but it is necessary to know from a bird`s-eye.

There are two distinct stages. Compilation and execution.

Compilation

The first stage consists of the code being parsed and compiled. Read more about this here. If there is any kind of syntax error this will be caught now and the interpreter aborts with a helpful error message before the actual execution starts.

==>notebook<==

Execution

Once the code is compiled the execution works exactly as you would expect: The interpreter reads the file line by line and executes all statements one after the other. Imports cause the execution to descend into the imported module, compile it, works through that line by line and pops back up. If the interpreter encounters a def or class statement, a function or class object is created and bound to the global namespace of the containing module.

To make it absolutely clear: the definition of classes and functions are normal statements which are executed the moment they are encountered by the interpreter. The result of the execution of those statements are the creation of objects that are bound to the current namespace (in this case the module namespace) pythontutor example.

==>notebook<==

But!

Although these stages are distinct, they intermingle, because it is only compiled what is needed, when it is needed. import is just another statement that gets executed in order, which means it is possible that the code runs smoothly for a while and then crashes with a syntax error, because a module with that error is imported later in the course of the program (e.g. an import that happens inside a function).

Resources