What Happens When You Run Python Code?
Source: Dev.to
A Simple Example
Let’s start with a simple Python program. Imagine we have a file called greet.py stored on our computer. Inside this file there’s a single function called greet():
# greet.py
def greet(name: str):
print(f"Hello {name}!")
If we call this function with the argument "drani":
greet(name="drani")
the program prints:
Hello drani!
Running the Python Program
To run the program we typically use the command:
python greet.py
When this command is executed, several things happen behind the scenes.
1. Loading the Code
The Python interpreter (CPython) loads the source file from disk into memory, preparing it for execution.
2. Compilation to Bytecode
The interpreter invokes its internal compiler, which performs several steps:
- Tokenization: The source code is broken into meaningful symbols called tokens.
- Building an Abstract Syntax Tree (AST): Tokens are organized into a tree structure that represents the program’s logic.
- Compiling to bytecode: The AST is transformed into Python bytecode, a lower‑level representation that the interpreter can execute efficiently.
If a cached version of the bytecode already exists in a .pyc file inside the __pycache__ directory, Python may load that instead of recompiling the source file, speeding up execution for frequently used modules.
3. Executing Bytecode
The CPython virtual machine executes the bytecode instruction by instruction. For each opcode:
- The interpreter dispatches the opcode to a corresponding C function that implements the operation.
- These C functions are compiled into native machine code that the CPU can understand.
- The CPU fetches, decodes, and executes these instructions, manipulating Python objects in memory as needed.
This process continues until all instructions have been executed.
4. Producing the Output
When execution completes, any resulting values are stored in memory. If the program includes output commands such as print(), the results are displayed to the user on the screen.
Conclusion
Even a simple program like greet.py involves several layers of processing under the hood: loading the file, compiling it to bytecode, and executing machine‑level instructions. Python hides much of this complexity, making it easy to write and run code while still being efficient and powerful. Understanding this process can help you write more efficient programs, troubleshoot performance issues, and better interpret errors when they occur.