Skip to main content

Command Palette

Search for a command to run...

🐍 Understanding How Python Code Works Internally

Published
3 min readView as Markdown

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 .pyc files 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

  • .pyc files 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:

VariantDescription
CPythonDefault and most widely used Python implementation (written in C).
JythonPython running on the Java Virtual Machine (JVM).
IronPythonPython for the .NET and C# ecosystem.
Stackless PythonOptimized version of Python for concurrency.
PyPyPython with a Just-In-Time (JIT) compiler for high performance.

🧾 Summary

StageDescriptionOutput
1️⃣ Write codeSource file (.py)Python code
2️⃣ CompileConverts to bytecode.pyc file
3️⃣ ExecuteBytecode runs on PVMProgram output

🔍 Key Notes

  • Bytecode is platform-independent.

  • .pyc files are stored in __pycache__ automatically.

  • Only imported files generate .pyc files.

  • PVM is the runtime engine that executes the bytecode.