🐍 How Python Runs Your Code

Raj VishwakarmaRaj Vishwakarma
2 min read

Ever wondered what happens behind the scenes when you run a Python script? Let’s break it down into simple steps—from code to output.


🔧 Step 1: Python Compiles Your Code to ‘ByteCode’

  1. Code Editor: The initial stage where programmers write source code in a human-readable format following Python's syntax rules. This is where program execution begins.

  2. Saving as .py File: The written code is saved as a .py file, which contains instructions for the computer in a human-readable language.

  3. Compilation to Bytecode: When a .py file is run, Python compiles it into bytecode, an intermediate representation of the code.

  4. Bytecode Characteristics: Bytecode is a low-level, platform-independent language. It executes faster than scripts because syntax errors are checked, and the bytecode is finalized. It is specific to Python and not machine code.

  5. Storage in pycache: The bytecode is stored as .pyc files in a __pycache__ folder. Although referred to as 'Frozen Binaries', it requires additional processing to produce the final output.

“Note: This pycache appears only when a non existing module is imported from other file not for top level files.”


♻️ Step 2: Bytecode Sent to Python Virtual Machine (PVM)

The bytecode then goes into the main part of the conversion is the Python Virtual Machine(PVM). The PVM is the main runtime engine of Python. It is an interpreter that reads and executes the bytecode file, line by line. Here In the Python Virtual Machine translate the byte code into machine code which is the binary language consisting of 0s and 1s. The machine code is highly optimized for the machine it is running on. This binary language is only understandable by the CPU of a system.


💡 Behind the Scenes (Simplified Flow)

.py file → Bytecode (.pyc) → PVM → Output

This process makes Python feel interpreted, but it actually uses a compile-then-interpret model.


⚙️ CPython, PyPy & Friends

  • CPython (mostly used) – Default, written in C

  • PyPy – Faster, uses JIT compilation

  • Jython – Python for Java platform

  • IronPython – Python on .NET


🧹 Garbage Collection

Python handles memory using:

  • Reference Counting

  • Cyclic Garbage Collection

You can also use the gc module for manual control.


🔬 Bonus: View Bytecode with dis

Want to see what Python runs under the hood?

import dis
dis.dis(lambda x: x + 1)

This shows actual bytecode like LOAD_FAST, BINARY_ADD.


✅ Conclusion

Even though Python feels high-level, it does a lot behind the scenes.


0
Subscribe to my newsletter

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

Written by

Raj Vishwakarma
Raj Vishwakarma