Python Internal Working

What is Python?

Python is a high-level, interpreted programming language.

  • High-level → You write code in a human-readable format (like English) rather than low-level machine instructions.

  • Interpreted → Python doesn’t directly convert your code into machine code (like C or C++), but it executes it line by line through an interpreter.


The Life Cycle of Python Code Execution

Let’s say you write a simple Python program in a file called hello.py:

print("Hello, World!")

Here’s how Python processes it internally:


Step 1: Writing the Code (Source Code)

  • You write your Python code using any text editor or IDE.

  • The file is saved with a .py extension, e.g., hello.py.

  • This is your source code → plain text instructions written in Python syntax.


Step 2: Compilation into Bytecode

When you run the program by typing:

python hello.py

✅ The Python interpreter first compiles your code into bytecode.

What is Bytecode?

  • Bytecode is a low-level, platform-independent set of instructions.

  • It’s not machine code (binary), but a more compact form of your source code.

  • Bytecode is saved as .pyc files (Python compiled files) inside the __pycache__ folder.

✔️ Example:
If you run hello.py, you’ll see __pycache__/hello.cpython-3xx.pyc (3xx as per Python version) created.

Step 3: Python Virtual Machine (PVM) Executes Bytecode

  • The Python Virtual Machine (PVM) is responsible for executing the bytecode.

  • It takes the .pyc file and interprets it line by line into machine instructions that the computer understands.

  • This is why Python is called an interpreted language.

Key Points:

  • Python compiles to bytecode, but the final execution happens through an interpreter (PVM).

  • The PVM reads and executes the bytecode instructions line by line.


Behind the Scenes: Components Involved

Python uses several components to make this process work:

🔹 Python Interpreter

The Python interpreter handles the entire process:

  • Compilation → From source code to bytecode.

  • Execution → Interpreting the bytecode using the PVM.

Python Execution

Let’s visualize the Python execution process:

Your Code (hello.py)  
     ↓  
[ Compilation ] → Bytecode (.pyc)  
     ↓  
[ PVM Interpretation ] → Machine Instructions  
     ↓  
[ Output on Screen ] → Hello, World!

When using imports in python

  1. When you use import, Python:

    • Compiles the module into bytecode.

    • Saves it as a .pyc file inside __pycache__.

  2. The .pyc file:

    • Speeds up execution by avoiding recompilation.

    • Is version-specific (e.g., cpython-313 for Python 3.13).

  3. You can:

    • Disable caching using -B or PYTHONDONTWRITEBYTECODE=1.

    • Decompile .pyc files to see the bytecode.

https://youtu.be/3HTKc-ZgZbg

0
Subscribe to my newsletter

Read articles from Shivangi Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shivangi Agarwal
Shivangi Agarwal