Understanding Python to Machine Code
When you run a Python script, have you ever wondered how it actually works? How a file able to become machine code? In this article, I will show you how with proof and couple of scripts you can use and follow along
Starter
I always have this curiosity on how things work under the hood. This is part of that journey of understanding how system works.
Let’s go deep into how Python code gets converted into something the CPU can eventually execute. I won’t just be explaining things with trust me bro. Instead, I’ll show you the source code and the evidence behind how I came to my conclusions through my own experiments. I'm just an explorer from the outside and not the developer of the Python Language so I may interpret some parts differently from what the original creators intended. Let's go.
Python Source
Python itself is known as the modern programming language used by wider profession and not just programmers and engineers but also researchers and scientists. It is use due to simplicity on writing and understanding the code syntax with extensive standard library and ecosystem to works on, meaning its easy to learn and start using it. However it is also known to be pain in the ass for developers (programmers and engineers) due to the fact its nature as high-level programming language. High-level languages are great for development speed, simplicity and having a large ecosystem but they generally come with trade off such as slower performance, higher memory usage and less direct control over computer hardware. It's very easy to prove these statement as we go into code later on.
Python syntax is very readable, check this out:
def main():
x = 10
y = 20
z = x + y
print(z)Can you guess what it does? Easy, right? From the code itself, you can see that it adds x + y, which results in 30 and then prints that result to the terminal. But did you know what actually happens inside the system? What are the process happening that causes you to be shown that result>
For C/C++ language, the source code will passthrough the compiler and it turns into machine code but for Python its way complicated than just run into compiler. In this journey, I'll break down the major stages involved in taking Python source code and getting it to the point where the CPU can execute the underlying operations. The example shown are the first step where developer write actual code for it to do something. Python is like other programming languages it's used to create a wide variety of programs that solve problems using computers.
Python source files can usually be identified by their .py file extension.
Tokenizer
After a developer create and writes a python file, 1_python_source.py, they'll want to execute the code, this'll require a python interpreter. Python interpreter is the program that is responsible for the source turn into the machine code. For this case, I'll use CPython as the implementation, it is the undisputed standard interpreter, over 95% of all Python developers use it.
One of the first things CPython has to do with Python source code is tokenization. Tokenization takes the characters written by the developer and breaks them into meaningful pieces called tokens. To see this for ourselves, we can use Python's built-in tokenize module. I'll create another Python script that opens our first Python source file and prints every token that the tokenizer produces.
import tokenize
with open("./1_python_source.py", "rb") as f:
for token in tokenize.tokenize(f.readline):
print(token) Then we run python 2_tokenizer.py, lets see what happen:
:!python /home/yasser/projects/active/python2machine/2_tokenizer.py
TokenInfo(type=68 (ENCODING), string='utf-8', start=(0, 0), end=(0, 0), line
='')
TokenInfo(type=1 (NAME), string='x', start=(1, 0), end=(1, 1), line='x = 10\
n')
TokenInfo(type=55 (OP), string='=', start=(1, 2), end=(1, 3), line='x = 10\n
')
TokenInfo(type=2 (NUMBER), string='10', start=(1, 4), end=(1, 6), line='x =
10\n')
TokenInfo(type=4 (NEWLINE), string='\n', start=(1, 6), end=(1, 7), line='x =
10\n')
TokenInfo(type=1 (NAME), string='y', start=(2, 0), end=(2, 1), line='y = 20\
n')
TokenInfo(type=55 (OP), string='=', start=(2, 2), end=(2, 3), line='y = 20\n
')
TokenInfo(type=2 (NUMBER), string='20', start=(2, 4), end=(2, 6), line='y =
20\n')
...
...
TokenInfo(type=1 (NAME), string='z', start=(4, 6), end=(4, 7), line='print(z
)\n')
TokenInfo(type=55 (OP), string=')', start=(4, 7), end=(4, 8), line='print(z)
\n')
TokenInfo(type=4 (NEWLINE), string='\n', start=(4, 8), end=(4, 9), line='pri
nt(z)\n')
TokenInfo(type=0 (ENDMARKER), string='', start=(5, 0), end=(5, 0), line='')I've removed a few lines from the output so it's easier to see what's happening. The important thing here is that the tokenizer doesn't treat the entire source code as full string anymore. It identifies individual pieces of the code and assigns each piece a token type. If we look closely here :
TokenInfo(type=1 (NAME), string='x', start=(1, 0), end=(1, 1), line='x = 10\
n')
TokenInfo(type=55 (OP), string='=', start=(1, 2), end=(1, 3), line='x = 10\n
')
TokenInfo(type=2 (NUMBER), string='10', start=(1, 4), end=(1, 6), line='x =
10\n')These are the tokens splits that source pieces each individual words are from this code x = 10 . You can also see the token type detected on each code like NAME, OP, NUMBER, NEWLINE . If you read the source code, you can understand how it actually works :
def tokenize(readline):
encoding, consumed = detect_encoding(readline)
rl_gen = _itertools.chain(consumed, iter(readline, b""))
if encoding is not None:
if encoding == "utf-8-sig":
# BOM will already have been stripped.
encoding = "utf-8"
yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__, encoding, extra_tokens=True)You can see, first few lines are to read the encoding of the file and label them respectively of their types. This is where the Python tokenize module hands the work over to CPython's C implementation of the tokenizer yield from _generate_tokens_ from_c_tokenizer (rl_gen.__next__, encoding, extra_tokens=True) . I mean looking at that line is not very interesting so I went deeper to find the actual C tokenizer. Funny enough, its pretty basic switch case which I didn't expect :
int _PyToken_OneChar(int c1)
{
switch (c1) {
case '!': return EXCLAMATION;
case '%': return PERCENT;
case '&': return AMPER;
case '(': return LPAR;
case ')': return RPAR;
case '*': return STAR;
case '+': return PLUS;
case ',': return COMMA;
case '-': return MINUS;
case '.': return DOT;
case '/': return SLASH;
case ':': return COLON;
case ';': return SEMI;
case '<': return LESS;
case '=': return EQUAL;
case '>': return GREATER;
case '@': return AT;
case '[': return LSQB;
case ']': return RSQB;
case '^': return CIRCUMFLEX;
case '{': return LBRACE;
case '|': return VBAR;
case '}': return RBRACE;
case '~': return TILDE;
}
return OP;
}That's the important thing to understand about this part.
Python source code starts as characters and the tokenizer begins turning those characters into structured tokens that later stages of CPython can work from.
Parser
I think before we dive into this one, we need to understand what parser does. Parser is a method on how it takes flat texts and turn it into structured format representation so we can get certain kind of arrangement for our system to consistently work with. For Python, one of the structured representations is the Abstract Syntax Tree (AST). Okay, let's see for ourselves :
import ast
with open("1_python_source.py", "r", encoding="utf-8") as file:
source = file.read()
tree = ast.parse(source)
print(ast.dump(tree, indent=4))We read the whole content of the file and run it to an Abstract Syntax Tree (AST) built-in from CPython. This is the result :
:!python /home/yasser/projects/active/python2machine/3_parser.py
[No write since last change]
Module(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=10)),
Assign(
targets=[
Name(id='y', ctx=Store())],
value=Constant(value=20)),
Assign(
targets=[
Name(id='z', ctx=Store())],
value=BinOp(
left=Name(id='x', ctx=Load()),
op=Add(),
right=Name(id='y', ctx=Load()))),
Expr(
value=Call(
func=Name(id='print', ctx=Load()),
args=[
Name(id='z', ctx=Load())]))])As you can see, the AST mapping will parse from tokenizer and represents its structural meaning. It assigned target z is the value of operation between x and y . You might wonder where tokenizer is as I didn't even use tokenize.tokenize but if you look at source code from import ast , what you'll find is :
def parse(source, filename='<unknown>', mode='exec', *,
type_comments=False, feature_version=None, optimize=-1):
flags = PyCF_ONLY_AST
if optimize > 0:
flags |= PyCF_OPTIMIZED_AST
......
# Else it should be an int giving the minor version for 3.x.
return compile(source, filename, mode, flags,
_feature_version=feature_version, optimize=optimize)ast.parse() isn't implementing an entirely separate Python parser in Python code. It eventually calls compile(..) . The flag allow us to use until a stage so we compile till AST instead till bytecode generation. In which if you go into their build-in module:
static PyObject *
builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
const char *mode, int flags, int dont_inherit,
int optimize, PyObject *modname, int feature_version)
/*[clinic end generated code: output=9a0dce1945917a86 input=444c4fe466a97279]*/
{
PyObject *source_copy;
const char *str;
int compile_mode = -1;
int is_ast;
int start[] = {Py_file_input, Py_eval_input, Py_single_input, Py_func_type_input};
PyObject *result;From there, the source eventually reaches CPython's parser process. You'll find the actual logic on how it runs where it is connected to mod = PyParserASTFromString (str, filename, start, flags, arena); which is the same spin off from tokenizer yield from _generate_tokens_ from_c_tokenizer (rl_gen.__next__, encoding, extra_tokens=True) . To be honest, I'm overwhelm since they use all these difference names but still pointing to the same C logic. Both of them typical flow connect to PyTokenizerGet() to split them, PEG Parser Engine to check the grammar rules and Abstract Syntax Tree (AST) to map structurally.
Modern CPython uses a Parsing Expression Grammar (PEG) parser to parse Python's grammar. The PEG parser takes the token stream and applies Python's grammar rules to determine how those tokens should be structured.
The tokenize module we used earlier is a public Python-level interface for tokenizing Python source. It is useful because it lets us inspect the tokens ourselves. However, the compiler's internal path is different. When CPython actually compiles Python source, its parser pipeline directly uses CPython's internal tokenizer and parser process. This is the part that is confusing at first but I figured out already. The names exposed don't always map one to one to internal C implementation. By the time we reach the AST, CPython has built a structured representation of what the Python program means syntactically.
Compiler
You might be wonder why an interpreted language have compiler since we often seeing interpreter vs compiler. But rest assured, I will explain to you. When we say that C is a compiled language and Python is an interpreted language, the distinction can be misleading. You need to understand, the terms are taught as opposite because its the easiest way to make people understand something complicated but they are actually the contains common stages with different implementation to execute a program. Let's see on higher view. This is a simplified CPython flow:
Python Source > Tokenizer > Parser > AST > Compiler (Bytecode) > CPython VM > CPU
This is a simplified GCC flow:
C Source > Preprocessor > Tokenizer > Parser > internal Representation (GIMPLE) > Optimizer > RTL > Assembler > Linker > Executable > CPU
As you can see, there are a lot of familiar terms on CPython as we've already go through parts of them but for GCC we never go through, so its okay not to understand all. It might seem like GCC does more work but python actually does more overall but is pushed towards the runtime more which we will get into later. The real biggest difference between them are compiler method and execution results, that's what make one consider as interpreter and another as just compiler. Therefore, CPython is an interpreter and contains a compiler.
Now back into CPython compiler. The compiler specifically took the AST and produces Python bytecode. That bytecode will then executed by Python Virtual Machine during runtime. Check this out:
filename = "1_python_source.py"
with open(filename, "r", encoding="utf-8") as file:
content_file = file.read()
code = compile(content_file, filename=filename, mode="exec")
print(type(code))
print(code)I ran the compile which will convert the source into bytecode and metadata which you may see different functions to dig some information:
:!python /home/yasser/projects/active/python2machine/4_compiler.py
<class 'code'>
<code object <module> at 0x7bf6392dbe30, file "1_python_source.py", line 1>Here are the code to look at the bytecode and its raw bytes produced:
import dis
filename = "1_python_source.py"
with open(filename, "r", encoding="utf-8") as file:
content_file = file.read()
code = compile(content_file, filename=filename, mode="exec")
dis.dis(code) # Bytecodes
print(code.co_code) # Raw bytes
print(code.co_names) # Names
print(code.co_consts) # ConstantsYou will see the bytecode but if you realise the bytecode isn't in a form of assembly language we're familiar with:
:!python /home/yasser/projects/active/python2machine/5_bytecode.py
0 RESUME 0
1 LOAD_SMALL_INT 10
STORE_NAME 0 (x)
2 LOAD_SMALL_INT 20
STORE_NAME 1 (y)
3 LOAD_NAME 0 (x)
LOAD_NAME 1 (y)
BINARY_OP 0 (+)
STORE_NAME 2 (z)
4 LOAD_NAME 3 (print)
PUSH_NULL
LOAD_NAME 2 (z)
CALL 1
POP_TOP
LOAD_CONST 1 (None)
RETURN_VALUE
b'\x80\x00^\nt\x00^\x14t\x01]\x00]\x01,\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00t\x02]\x03!\x00]\x024\x01\x00\x00\x00\x00\x00\x00\x1f\x00R\x01#\x00'
('x', 'y', 'z', 'print')
(10, None)That's because the bytecode is used for Python Virtual Machine instead of our computer hardware.
Python Virtual Machine
Now we have reached one of the most interesting parts of CPython, the Python Virtual Machine (VM). The Python VM takes the bytecode produced by the compiler and dispatches each instruction to the corresponding implementation inside the CPython interpreter. It is part of the interpreter that executes standardized instruction set. Rather than believing me, let's check the source code:
#if !_Py_TAIL_CALL_INTERP
#if !USE_COMPUTED_GOTOS
dispatch_opcode:
switch (dispatch_code)
#endif
{
#endif /* _Py_TAIL_CALL_INTERP */
/* BEGIN INSTRUCTIONS */
TARGET(BINARY_OP) {
#if _Py_TAIL_CALL_INTERP
int opcode = BINARY_OP;
(void)(opcode);
#endif
frame->instr_ptr = next_instr;
... // shorten for better visual
_Py_CODEUNIT* const this_instr = next_instr - 6;
(void)this_instr;
{
value = l;
stack_pointer += -1;
ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
_PyFrame_SetStackPointer(frame, stack_pointer);
_PyFrame_StackPointerValidate(frame);
PyStackRef_XCLOSE(value);
_PyFrame_StackPointerInvalidate(frame);
}
DISPATCH();
}
TARGET(BINARY_OP_ADD_FLOAT) {
#if _Py_TAIL_CALL_INTERP
int opcode = BINARY_OP_ADD_FLOAT;
(void)(opcode);
#endif
_Py_CODEUNIT* const this_instr = next_instr;
... // shorten for better visualAs this part, you can find each bytecode from dis.dis(code) actually have their respective C function to be run under the Python VM. So what will they do with those? Let's find out:
PyObject* _Py_HOT_FUNCTION DONT_SLP_VECTORIZE
_PyEval_EvalFrameDefault(PyThreadState *tstate, _PyInterpreterFrame *frame, int throwflag)
{
_Py_EnsureTstateNotNULL(tstate);
check_invalid_reentrancy();
CALL_STAT_INC(pyeval_calls);
...
#if !_Py_TAIL_CALL_INTERP
uint8_t opcode; /* Current opcode */
int oparg; /* Current opcode argument, if any */
assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
#if !USE_COMPUTED_GOTOS
uint8_t tracing_mode = 0;
uint8_t dispatch_code;
#endif
...
#if _Py_TAIL_CALL_INTERP
# if Py_STATS
return _TAIL_CALL_error(frame, stack_pointer, tstate, next_instr, instruction_funcptr_handler_table, 0, lastopcode);
# else
return _TAIL_CALL_error(frame, stack_pointer, tstate, next_instr, instruction_funcptr_handler_table, 0);
# endif
#else
goto error;
#endif
}
#if _Py_TAIL_CALL_INTERP
# if Py_STATS
return _TAIL_CALL_start_frame(frame, NULL, tstate, NULL, instruction_funcptr_handler_table, 0, lastopcode);
# else
return _TAIL_CALL_start_frame(frame, NULL, tstate, NULL, instruction_funcptr_handler_table, 0);
# endif
#else
goto start_frame;
# include "generated_cases.c.h"
#endif
...Under PyEvalEvalFrameDefault() , you could find _Py_TAIL_CALL_INTERP . With the tail-call approach, the interpreter can transition from one instruction handler to the next through a chain of calls rather than relying on the traditional central dispatch loop. The other approach uses a loop that repeatedly fetches and dispatches the next bytecode instruction. They basically evaluates a python frame. A frame represents an executing Python scope like instruction pointer, stack and local state.
Reminder, CPython does not convert or translate the bytecode into C code, when CPython is built, the C source are already compiled into an executable machine code.
So when bytecode is produced, the interpreter just redirect to operation to perform so its not like gcc compile.c every time but more like ./compile bytecode.py (this isn't the accurate depiction internally but it may help you illustrate the difference)
Finally
Now you can see the simplified full flow on how Python intepreter works! You also should realise why Python generally consider slower performance compare to low level programming language like C and C++. If you haven't, it's because there's additional flow on runtime where it need to translates python source into bytecode into CPython VM and then only to the CPU. Of course, Python developers can still optimize their programs and Python can make use of highly optimized native libraries written in C, C++, Rust or other languages.
High-level languages are great for development speed, simplicity and having a large ecosystem but they generally come with trade off such as slower performance, higher memory usage and less direct control over computer hardware.
And that's all the trade-off we've been discussing throughout this article. Thank you for reading to the end. This was hard for me to write so I can only imagine how hard it was to read.