Python Is Not Running Your Code (Execution Model Deep Dive)
You write Python.
But Python is not executing your code the way you think.
Today, you stop treating Python as magic.
Today’s Goal
By the end of today, you will:
- Understand how Python executes your code
- Learn what happens between
.pyto execution - Build a mental model of the Python interpreter
The Illusion
You write:
x = 10
y = x + 5
print(y)
You assume:
Python reads this line by line and runs it
That assumption is wrong.
The Real Pipeline
Your code goes through three stages:
Source Code (.py)
|
v
Compilation -> Bytecode (.pyc)
|
v
Execution -> Python Virtual Machine (PVM)
Step 1 - Compilation
Before execution, Python converts your code into:
Bytecode
This is a low-level instruction set designed for the interpreter.
Example (Conceptual Bytecode)
LOAD_CONST 10
STORE_NAME x
LOAD_NAME x
LOAD_CONST 5
BINARY_ADD
STORE_NAME y
LOAD_NAME y
PRINT
This is what Python actually executes, not your original code.
Where Is This Stored?
Python may generate:
__pycache__/
file.cpython-311.pyc
This .pyc file contains:
- compiled bytecode
- optimized for faster startup
Important Insight
Python is compiled to bytecode, then interpreted.
Step 2 - The Python Virtual Machine (PVM)
This is the engine that runs your code.
Execution Loop (Simplified)
while instructions exist:
fetch instruction
execute instruction
What This Means
Every line of your code becomes:
- multiple instructions
- executed one by one
- inside a loop
Key Insight
Python execution is a loop over bytecode instructions.
Why This Matters
Because:
- Each operation has overhead
- Python is slower than compiled languages
- Performance is tied to instruction count
Inspect It Yourself
Use the built-in disassembler:
import dis
def f():
x = 10
return x + 5
dis.dis(f)
Example Output
LOAD_CONST 10
STORE_FAST x
LOAD_FAST x
LOAD_CONST 5
BINARY_ADD
RETURN_VALUE
One line becomes multiple operations.
Mental Model Upgrade
Before: Python runs my code
Now: Python executes bytecode instructions in a loop
Hidden Cost
Even simple operations involve:
- stack operations
- reference handling
- interpreter dispatch
Performance Insight
This is why:
- Python loops are slower
- function calls are expensive
- optimized libraries use C
Your Task
- Write a small function
- Run:
import dis
- Observe:
- number of instructions
- how simple code expands
Common Mistakes
- Thinking Python runs code directly
- Ignoring bytecode layer
- Assuming one line equals one operation
- Not understanding execution cost
Think Deeper
- Why does Python compile to bytecode instead of machine code?
- Why is Python slower than C?
- What happens if
.pycfile is deleted?
Final Insight
Python is a virtual machine executing instructions, not your source code.
Tomorrow
Memory model - objects, references, mutability
Rule
- Build mental models
- Question assumptions
See you in Day 2.