How Python Works
Demystify what happens under the hood when you run Python code, from source code parsing and bytecode compilation to the Python Virtual Machine.
In setup-environment, you learned how to type python script.py into your terminal and see results appear on your screen. But what actually happens inside your computer during the split-second between pressing Enter and seeing the output?
Many tutorials simply call Python an “interpreted language” and leave it at that. In reality, Python uses a modern, two-stage execution model that combines the best parts of both compilation and interpretation.
Understanding this architecture turns Python from a black box of magic into a clear, predictable engine.
Compilers vs. Interpreters: The Book Translation Analogy
To understand Python’s approach, consider how human languages are translated into a foreign language:
1. Purely Compiled Languages (C, C++, Rust, Go)
- The Analogy: A publisher takes an entire English book, hires a translator, translates the entire book into French once, and prints thousands of copies.
- In Programming: A compiler reads your entire source code file, checks for errors, and translates it directly into native machine code (binary
0s and1s) tailored specifically to your exact computer chip (Intel, AMD, or Apple Silicon). - Trade-off: The build step takes time upfront, but the resulting executable file runs blistering fast and requires no external translator program to be installed on the user’s computer.
2. Purely Interpreted Languages (Early BASIC, Shell scripts)
- The Analogy: A live United Nations interpreter sitting in a booth, listening to each spoken sentence and translating it on the fly into an earpiece, sentence by sentence.
- In Programming: An interpreter reads code line by line, executing each statement immediately as it encounters it.
- Trade-off: Fast to start and easy to experiment with, but slower to run because the computer must re-translate the exact same loops and sentences repeatedly.
Python’s Two-Stage Execution Model
Python does not pick one extreme—it uses a hybrid model. When you run a script, Python executes two distinct stages:
+------------------+
| Source Code | (Your hello.py file written in readable Python)
+------------------+
|
| Stage 1: Bytecode Compilation (Automatic & In-Memory)
v
+------------------+
| Bytecode | (Platform-independent instructions: LOAD_CONST, BINARY_OP)
| (__pycache__/) |
+------------------+
|
| Stage 2: Execution via PVM (Python Virtual Machine)
v
+------------------+
| PVM | (Evaluates bytecode instructions and manages memory)
+------------------+
|
| Hardware Execution
v
+------------------+
| Your CPU | (Physical calculations & system output)
+------------------+
Stage 1: Compilation to Bytecode
When you execute a script, the Python engine first checks your code for syntax mistakes. If the syntax is valid, it compiles your human-friendly text into an intermediate format called bytecode.
Bytecode is not native CPU machine code. Instead, it is a compact set of instructions designed for an idealized, simulated computer called the Python Virtual Machine.
Because bytecode is not tied to a specific processor brand or operating system, the exact same bytecode can run on Windows, macOS, Ubuntu, or an Android phone without changes.
Stage 2: Execution via the Python Virtual Machine (PVM)
Once bytecode is generated, it is fed into the Python Virtual Machine (PVM). The PVM is a software loop inside the Python interpreter that reads each bytecode instruction and executes the corresponding native machine operations on your real hardware.
What is That __pycache__ Folder?
If you have ever imported a Python file or built a project, you have likely noticed a folder named __pycache__ appearing automatically with files ending in .pyc (like helper.cpython-312.pyc).
Many beginners worry that they created this folder by mistake or that it is malware. It is completely normal!
Here is why it exists:
- Compiling source code into bytecode takes a few milliseconds of CPU time.
- When Python imports a module, it caches the compiled bytecode inside
__pycache__. - On subsequent runs, Python checks the timestamp of your
.pysource file against the.pyccache file. If you have not changed the code, Python skips Stage 1 entirely and loads the cached bytecode directly, speeding up application startup time.
You never need to edit or touch files inside
__pycache__. If you delete the folder, Python will simply recreate it the next time your code runs.
What is CPython?
When people say “Python,” they usually mean two different things:
- The Python Language: The syntax rules, keywords, and grammar you write (like
print(),def, andimport). - The Python Implementation: The actual software program running on your computer that executes those rules.
The standard, default implementation you downloaded from python.org is called CPython. It is written in the C programming language and is maintained by the core Python engineering team.
Other alternative Python implementations exist for specialized needs:
- PyPy: Uses a Just-In-Time (JIT) compiler to run computational Python code up to 4x faster.
- MicroPython: An ultra-compact Python interpreter designed to run on tiny microcontrollers and hardware robotics boards with only a few kilobytes of RAM.
- Jython & IronPython: Implementations designed to integrate with Java (JVM) and .NET environments.
Peeking Under the Hood: The dis Module
You can actually see the bytecode that Python generates using Python’s built-in disassembler module, named dis.
Create a small function and disassemble it:
import dis
def add_numbers(a, b):
return a + b
# Print the underlying bytecode instructions
dis.dis(add_numbers)
Output:
1 0 RESUME 0
2 2 LOAD_FAST 0 (a)
4 LOAD_FAST 1 (b)
6 BINARY_OP 0 (+)
10 RETURN_VALUE
Look at the instructions the PVM receives:
LOAD_FAST 0 (a): Fetch the first parameteraand place it onto Python’s execution stack.LOAD_FAST 1 (b): Fetch the second parameterband place it onto the stack.BINARY_OP 0 (+): Pop both values, add them together, and place the result back on the stack.RETURN_VALUE: Return the top value to the caller.
Even the most complex web applications and machine learning models break down into these clean, discrete stack instructions.
Automatic Memory Management & Garbage Collection
In low-level languages like C or C++, programmers must manually calculate how many bytes of memory their program needs, ask the operating system for that memory, and remember to free it when finished. If they forget, the program leaks memory and crashes the computer.
Python protects you from this through Automatic Memory Management:
- Reference Counting: Python tracks how many variables are pointing to every object in memory.
- Garbage Collector: When an object’s reference count drops to zero (meaning no part of your program is using it anymore), Python automatically reclaims that memory block for reuse.
You can learn more about how memory optimization works in production systems in memory-performance.
Summary Checklist
- Two-Stage Process: Python compiles
.pysource text to bytecode, then runs that bytecode inside the Python Virtual Machine (PVM). - Portability: Bytecode is platform-independent, allowing Python code to run anywhere the PVM is installed.
__pycache__: Caches.pycbytecode on disk to accelerate application startup.- Garbage Collection: Python automatically manages and frees memory so you can focus on building logic.
Now that you understand the mechanics of the engine, head over to syntax-and-comments to learn how Python programs are structured and how to write clean, documented code.