Python interpreter and bytecode

I have a doubt whether python converts all code into bytecode at the same time and then feed it to the python virtual machine line by line. Or it converts code into bytecode line by line while simultaneously feeding that line of bytecode to a python virtual machine for execution.
And when python raises an error during bytecode conversion or during bytecode execution.?

The CPython interpreter always converts a Python source code file at a whole into bytecode, then executes it entirely. For scripts, this happens on the fly. However, when you import a module, its bytecode is cached (in the __pycache__ directory) so subsequent imports are slightly faster.

Syntax errors are raised during parsing, that is, before any execution can happen. This is why you cannot catch a SyntaxError in your main program. Try, for instance:

try:
    invalid syntax!
except SyntaxError:
    print("Cought")

This yields:

  File "<tmp 1>", line 2
    invalid syntax!
            ^
SyntaxError: invalid syntax

However, if the syntax error is in another module, it can still be caught. With mymodule.py containing

invalid syntax!

the code

try:
    import mymodule
except SyntaxError:
    print("Cought")

outputs

Cought

Nearly all other errors are raised at runtime because Python is so dynamic. This includes NameErrors for example. There might be an exception somewhere that I can’t remember, but that’s the general idea.

1 Like