Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly is Python Bytecode Run in CPython?

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?

like image 364
mergesort Avatar asked Nov 11 '13 21:11

mergesort


People also ask

How does Python execute bytecode?

The default implementation of the Python programming language is CPython which is written in the C programming language. CPython compiles the python source code into the bytecode, and this bytecode is then executed by the CPython virtual machine. All the generated pyc files will be stored in the __pycache__ folder.

Is CPython a compiler or interpreter?

CPython can be defined as both an interpreter and a compiler as it compiles Python code into bytecode before interpreting it. It has a foreign function interface with several languages, including C, in which one must explicitly write bindings in a language other than Python.

How bytecode is executed?

A bytecode program may be executed by parsing and directly executing the instructions, one at a time. This kind of bytecode interpreter is very portable. Some systems, called dynamic translators, or just-in-time (JIT) compilers, translate bytecode into machine code as necessary at runtime.

Is CPython a compiled language?

The default and most popular implementation of Python is CPython. There is an important advantage of using it. C is a compiled language and its code is converted into machine code, which is executed directly by the central processing unit (CPU).


1 Answers

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.

like image 88
georg Avatar answered Sep 28 '22 06:09

georg