How Python Works Internally: Bytecode, PVM, CPython
Python tutorial · PySpark.in
Python works internally in four steps: your source code is tokenized, parsed into an abstract syntax tree (AST), compiled to bytecode, and executed by the Python Virtual Machine (PVM) inside CPython. So Python is both compiled and interpreted. This guide walks through each step with code you can run.
Python is often praised for its simplicity: you write a few lines of code, run it, and it just works. But have you ever wondered what happens in the backend when you run Python code?
Behind its beginner-friendly syntax, Python has a powerful internal mechanism that involves parsing, compiling, interpreting, and execution. Understanding this flow helps developers write efficient code and appreciate the language’s design.
The Lifecycle of a Python Program
When you run a Python file (say, python myscript.py), here’s what happens step by step:
1. Source Code (.py file)
Your human-readable code is written in a .py file, for example:
2. Lexical Analysis (Tokenization)
Python first reads the source code and breaks it down into small pieces called tokens (keywords, identifiers, operators, etc.).
Example:
gets tokenized into:
-
print→ function name -
(→ open parenthesis -
"Hello, Python!"→ string literal -
)→ closing parenthesis
3. Parsing
The tokens are then arranged into a Parse Tree (or Abstract Syntax Tree – AST) that represents the grammatical structure of your code.
For example, print("Hello, Python!") becomes an AST node representing a function call with a string argument.
4. Compilation to Bytecode
Next, Python converts the AST into bytecode, which is a low-level set of instructions understood by the Python interpreter.
This bytecode is stored in .pyc files (inside the __pycache__ folder). For example, when you import mymodule, CPython 3.12 caches it as __pycache__/mymodule.cpython-312.pyc and reuses it next time if the source has not changed. The script you run directly (python myscript.py) is compiled in memory every time and is not cached.
Bytecode is platform-independent: the same .pyc works on Windows, Linux or macOS. It is tied to the Python version, though, so a .pyc written by 3.12 is ignored and rebuilt by 3.13.
5. Python Virtual Machine (PVM)
The bytecode is then fed into the Python Virtual Machine (PVM), which is essentially the interpreter loop. The PVM executes each bytecode instruction one by one.
-
This step is why Python is often called an interpreted language (though technically it’s compiled to bytecode first, then interpreted).
-
The PVM is the “engine” that makes Python code run.
See each step yourself
The standard library exposes every stage. Run these blocks to see the tokens and AST for print("Hello, Python!"), then the bytecode of a small function (the exact instructions depend on your Python version):
```
import ast, io, tokenize
src = 'print("Hello, Python!")'
# Step 2: tokens
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
if tok.string.strip():
print(tokenize.tok_name[tok.type], repr(tok.string))
# Step 3: the abstract syntax tree
print(ast.dump(ast.parse(src).body[0], indent=2))
```
```
import dis
def add(a, b):
return a + b
# Step 4: the bytecode the PVM will execute
dis.dis(add)
# compile() runs the same compiler; 2 + 3 is already folded to 5
code = compile("x = 2 + 3\nprint(x)", "demo.py", "exec")
print(code.co_consts)
exec(code) # Step 5: the PVM runs it
```
Is Python compiled or interpreted?
Both. CPython first compiles your source to bytecode, then the PVM interprets that bytecode. What Python does not do by default is compile to machine code ahead of time, as C or Go do, which is why it is usually described as an interpreted language. PyPy adds a just-in-time (JIT) compiler that turns hot bytecode into machine code, and CPython 3.13 ships an experimental JIT that is off by default.
The Role of CPython, PyPy, and Others
When people say “Python,” they usually mean CPython, the default implementation written in C. CPython handles all the steps above.
Other implementations exist:
-
PyPy → Uses Just-In-Time (JIT) compilation for faster execution.
-
Jython → Runs Python on the Java Virtual Machine (JVM).
-
IronPython → Runs Python on the .NET framework.
Each implementation has its own way of handling bytecode and execution, but the overall workflow remains similar.
Memory Management in Python
Python also manages memory in the backend using:
-
Private Heap → All Python objects and data structures are stored in a private heap.
-
Memory Manager → Allocates and releases memory automatically.
-
Garbage Collector → Removes unused objects using reference counting and a cyclic garbage collector.
This is why developers rarely worry about memory allocation in Python—it’s all automated.
You can watch reference counting and the cyclic collector at work:
```
import gc, importlib.util, sys
# Where CPython caches the bytecode of an imported module
print(importlib.util.cache_from_source("mymodule.py"))
# Reference counting: each name and argument holding the object adds one
data = []
print("references:", sys.getrefcount(data))
# Two lists that point at each other never reach zero references:
# the cyclic garbage collector frees them
a, b = [], []
a.append(b)
b.append(a)
del a, b
print("unreachable objects collected:", gc.collect())
```
The GIL: why one process runs one bytecode at a time
CPython has a Global Interpreter Lock (GIL): only one thread executes Python bytecode at a time in a process. It keeps reference counting safe without locking every object. Threads still help with I/O, because the GIL is released while a thread waits on the network or disk, but CPU-heavy work needs multiprocessing, C extensions such as NumPy that release the GIL, or a distributed engine such as PySpark. Python 3.13 also offers an experimental free-threaded build without the GIL.
Putting It All Together
Here’s a simplified diagram of how Python works:
Example with print("Hello, Python!"):
-
Code written →
print("Hello, Python!") -
Tokenized →
['print', '(', 'Hello, Python!', ')'] -
Parsed → Function call node in AST
-
Compiled → Bytecode instructions (
LOAD_NAME,LOAD_CONST,CALL; exact names vary by Python version) -
Executed → PVM runs → Output:
Hello, Python!
Why Should You Care About Python Internals?
-
Performance Tuning: Knowing that the PVM interprets bytecode one instruction at a time explains why it’s slower than compiled languages like C++.
-
Debugging: Understanding
.pycfiles and the PVM helps diagnose runtime issues. -
Choosing the Right Implementation: For performance-heavy tasks, PyPy or Cython may be better than CPython.
-
Efficient Code Writing: Awareness of memory management can guide you in writing cleaner, faster code.
Conclusion
Python may look simple on the surface, but behind the scenes it follows a well-defined process: source code → tokens → AST → bytecode → PVM execution. This combination of compilation and interpretation is what makes Python flexible and powerful.
FAQ: how Python works internally
What is the PVM in Python? The Python Virtual Machine is the loop inside the interpreter that reads bytecode instructions and executes them one by one. In CPython it is written in C.
What is CPython? The reference implementation of Python, written in C, that you download from python.org. It contains the compiler, the PVM, the memory manager and the standard library.
Where are .pyc files stored? In a __pycache__ folder next to the module, named with the interpreter and version, for example mymodule.cpython-312.pyc. They are created when a module is imported, not for the script you run.
Why is Python slower than C? The PVM interprets bytecode at run time and every value is a full object with a type check, while C is compiled ahead of time to machine code. Libraries such as NumPy and PySpark move the heavy work into compiled code.
Keep learning Python
- Python data types explained
- Python modules and imports: where __pycache__ comes from.
- Top 30 Python interview questions: internals questions come up often.
- What is Python and why it is used for data engineering
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- Introduction To Python
- Encapsulation in Python
All tutorials · Try the free PySpark compiler · Practice challenges