🐍 Understanding How Python Code Works Internally
Here’s a clean, professional documentation-style explanation of how Python works — formatted clearly, like what you’d write in Notion or technical documentation Understanding How Python Code Works Internally
When you write and run a Python program, several steps happen behind the scenes before your code executes. Let’s break down the entire process.
⚙️ Step 1: Source Code (.py)
You start by writing your Python code in a .py file.
Example:
# first.py
def greet():
print("Hello from first file!")
Then in another file:
# second.py
from first import greet
greet()
When you run:
python3 second.py
Python automatically creates a folder called __pycache__ and stores a compiled version of the imported module inside it (for example, first.cpython-312.pyc).
🧩 Step 2: Compilation to Bytecode
Before execution, Python compiles your .py source code into bytecode — a low-level, platform-independent representation of your code.
Bytecode is not machine code.
It’s a Python-specific intermediate code that runs faster than raw source code.
These compiled files are saved as
.pycfiles inside the__pycache__folder.
💡 Example:first.cpython-312.pyc → compiled with CPython 3.12 version.
📦 Step 3: Execution by the Python Virtual Machine (PVM)
Once the code is compiled into bytecode, the Python Virtual Machine (PVM) takes over.
The PVM interprets and executes the bytecode instructions line by line.
It acts as the runtime engine of Python.
This step is why Python is known as an interpreted language.
🧠 In short:
Python → compiles to bytecode → runs on Python Virtual Machine (PVM)
📁 Step 4: .pyc Files and Their Behavior
.pycfiles are auto-generated only for imported modules (not for top-level scripts you run directly).These files help speed up execution next time — since the bytecode is already compiled.
Example:
project/
│
├── first.py
├── second.py
└── __pycache__/
└── first.cpython-312.pyc
🧠 Variants of the Python Interpreter
Python has multiple implementations — all follow the same concept but use different underlying technologies:
| Variant | Description |
| CPython | Default and most widely used Python implementation (written in C). |
| Jython | Python running on the Java Virtual Machine (JVM). |
| IronPython | Python for the .NET and C# ecosystem. |
| Stackless Python | Optimized version of Python for concurrency. |
| PyPy | Python with a Just-In-Time (JIT) compiler for high performance. |
🧾 Summary
| Stage | Description | Output |
| 1️⃣ Write code | Source file (.py) | Python code |
| 2️⃣ Compile | Converts to bytecode | .pyc file |
| 3️⃣ Execute | Bytecode runs on PVM | Program output |
🔍 Key Notes
Bytecode is platform-independent.
.pycfiles are stored in__pycache__automatically.Only imported files generate
.pycfiles.PVM is the runtime engine that executes the bytecode.