How exactly is Python Bytecode Run in CPython?

mergesort picture mergesort · Nov 11, 2013 · Viewed 12k times · Source

I am trying to understand how Python works (because I use it all the time!). To my understanding, when you run something like python script.py, the script is converted to bytecode and then the interpreter/VM/CPython–really just a C Program–reads in the python bytecode and executes the program accordingly.

How is this bytecode read in? Is it similar to how a text file is read in C? I am unsure how the Python code is converted to machine code. Is it the case that the Python interpreter (the python command in the CLI) is really just a precompiled C program that is already converted to machine code and then the python bytecode files are just put through that program? In other words, is my Python program never actually converted into machine code? Is the python interpreter already in machine code, so my script never has to be?

Answer

georg picture georg · Nov 11, 2013

Yes, your understanding is correct. There is basically (very basically) a giant switch statement inside the CPython interpreter that says "if the current opcode is so and so, do this and that".

http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790

Other implementations, like Pypy, have JIT compilation, i.e. they translate Python to machine codes on the fly.