Absolutely! Let's explore how Python code is executed step by step — from the moment you write it to when it's actually run on your machine.
🧠 High-Level Overview
Python is an interpreted, high-level, general-purpose programming language. This means that Python code is not compiled into machine code (binary) ahead of time, but rather interpreted and executed line-by-line, or more precisely, transformed into bytecode and then executed by the Python Virtual Machine (PVM).
🧭 Step-by-Step Execution (Detailed)
Step 1️⃣: Write the Python Code
You create a Python source file, for example:
# example.py
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
This is a plain text .py file with valid Python syntax.
Step 2️⃣: The Interpreter is Invoked
When you run this code (e.g., python example.py on the command line), the Python interpreter is used to process the file.
Python is interpretable via implementations like:
- CPython (default)
- PyPy
- Jython
- IronPython
We’ll focus on CPython, the most common one.
Step 3️⃣: Lexing (Tokenization)
The source code is converted into a stream of tokens.
For example:
def greet(name):
becomes tokens like:
def → keyword
greet → identifier
( → left parenthesis
name → identifier
) → right parenthesis
: → delimiter
This is handled by the lexer/scanner.
Step 4️⃣: Parsing
The tokens are then passed to the parser, which checks that the code follows Python grammar rules. It creates an Abstract Syntax Tree (AST) — a tree structure representing the grammatical structure of the code.
Example AST for our code:
Module
├── FunctionDef (greet)
│ ├── arguments: name
│ └── body:
│ └── Expr:
│ └── Call: print(f"Hello, {name}!")
└── Expr:
└── Call: greet("Alice")
Step 5️⃣: Compilation to Bytecode
Python then compiles the AST into bytecode — a lower-level, platform-independent representation of your code.
This is NOT machine code; it’s an intermediate form for execution by the Python Virtual Machine.
- The bytecode is stored in
.pyc files, inside __pycache__/ folders for reuse.
- You can view the bytecode using Python’s built-in module:
import dis
def greet(name):
print(f"Hello, {name}!")
dis.dis(greet)
This shows Python's bytecode instructions for the function.
Example:
2 0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Hello, ')
4 LOAD_FAST 0 (name)
6 FORMAT_VALUE 0
8 BUILD_STRING 2
10 CALL_FUNCTION 1
12 POP_TOP
Step 6️⃣: Execution by Python Virtual Machine (PVM)
Now, the bytecode is handed over to the Python Virtual Machine (PVM).
PVM is part of the CPython runtime. It reads the bytecode and executes it instruction by instruction, interacting with:
- Memory (variables, function calls)
- Stack (for managing execution context)
- OS (for print statements or IO)
- Built-in libraries
This is the "interpreter" part — it interprets bytecode at runtime.
Step 7️⃣: Output is Produced
In our case, the PVM:
- Calls the function
greet("Alice")
- Executes the
print(f"Hello, {name}!") instruction,
- You see this on the screen:
Hello, Alice!
🧠 Summary of Execution Steps
| Step | Description |
|---|
| 1 | Code is written in a .py file |
| 2 | Python interpreter reads the file |
| 3 | Source code -> Tokens (tokenization) |
| 4 | Tokens -> AST (parsing) |
| 5 | AST -> Bytecode (compilation) |
| 6 | Bytecode -> Machine executes via PVM |
| 7 | Output is generated |
📌 Optional: .pyc Files
If you’ve noticed __pycache__/example.cpython-311.pyc — this is Python caching the bytecode so next time it doesn't need to recompile from source.
🧪 Try It Yourself (Mini Project Idea)
You can inspect each phase:
python -m tokenize example.py # Step 3: Tokenization
python -m ast example.py # Step 4: AST
python -m dis example.py # Step 5: Bytecode
🔥 Extra (Advanced)
- Python uses a stack-based virtual machine, not a register-based one (like JVM).
- No true compilation to native CPU instructions in CPython (unlike C++ or Rust).
- You can use
compile(), exec, eval() to control execution manually!
Example:
code = "print('Hello from manual compile!')"
compiled = compile(code, '<string>', 'exec')
exec(compiled)
Let me know if you'd like a diagram or visual version of this pipeline!