⚙️ What Happens When You Run a .py File
When you type python hello.py, the Python interpreter doesn't directly execute your code. Instead, it travels through three stages: reading the source code, translating it to bytecode, then executing it on the Python Virtual Machine (PVM).
This journey—unlike compiled languages like C where the entire file becomes a binary before running—happens on-demand. Python reads and compiles what it needs, when it needs it. That's why Python is called "interpreted."
Understanding this three-stage process is the key to debugging slow code, deploying Python to production, and knowing why Python feels both easy and fast for AI work.
🔧 5 Key Components in Python Execution
📍 A Real Scenario: Aisha in Nairobi Runs Her First Script
Aisha just finished writing her first Python script on her MacBook in Nairobi. It reads a list of M-Pesa transactions and calculates the average. She types python transactions.py and it runs instantly—taking 0.2 seconds. She wonders: Did Python compile my code first? Where does the 0.2 seconds go? Where are the compiled files?
In that 0.2 seconds, three things happened that Aisha didn't see. The interpreter parsed her code, compiled it to bytecode, stored it (invisibly), and executed it on the PVM. If she runs the script again, it's faster because Python reuses the bytecode. If she'd written the same script in C, she'd manually compile it first—a separate step. Python hides compilation from you.
🚀 Step-by-Step: Running a Python Script
Let's trace what happens when you run a simple "hello" program. Here's the journey in 4 stages.
Stage 1: Source Code (What You Write)
Stage 2: Parsing & Compilation to Bytecode
The interpreter reads your source code and translates it into bytecode—a low-level, portable instruction set. Python stores this in .pyc files (bytecode cache) inside a __pycache__/ folder.
This bytecode is stored in __pycache__/hello.cpython-39.pyc (the version number depends on your Python version). You never see these files normally—Python manages them automatically.
Stage 3 & 4: PVM Execution
The PVM (Python Virtual Machine) reads each bytecode instruction, one by one, and executes it. It manages a call stack (for function calls), a heap (for objects like lists and strings), and references to built-in operations.
Key insight: The bytecode is portable. The same .pyc file can run on any machine that has a PVM installed—Windows, Linux, or a Raspberry Pi in a warehouse in Mumbai. That portability is why Python runs everywhere.
🔀 Interpreted vs. Compiled: The Real Difference
Python is interpreted—but not in the way you might think. The truth is more nuanced and explains why Python feels slow for tight loops but fast for data science.
What "Interpreted" Really Means
An interpreted language compiles source code to bytecode on-the-fly and executes it immediately (or caches the bytecode). A compiled language compiles the entire source to machine code upfront, producing an executable binary that you run separately.
Comparison: Python vs. C vs. Java
Why this matters in practice:
- Python: Faster feedback loop (no compile step = faster iteration). Slower at runtime (bytecode → PVM is slower than machine code).
- C: Slow feedback (must compile before running). Faster at runtime (machine code runs at CPU speed).
- Java: Hybrid approach—compile once, run anywhere (like Python), but with more upfront compilation overhead.
The Python trick for speed: Core libraries (NumPy, PyTorch) are written in C and called from Python. You get Python's ease + C's speed. This is why import numpy as np then calling np.dot(A, B) is fast—the heavy math runs in compiled C code, not bytecode.
🔒 The Global Interpreter Lock (GIL) in One Sentence
The GIL ensures only one thread executes Python bytecode at a time, even on multi-core CPUs—so multi-threaded Python doesn't get true parallelism, but it's fine for IO-bound work (web requests, file reads) since threads pause when waiting for IO.
Practical takeaway: For CPU-bound work (loops, math), use multiprocessing instead of threading. For IO-bound work (API calls, databases), threading or asyncio is fine.
💾 Memory Management Basics
Python uses automatic garbage collection. You don't manually free memory like in C (where you call free()). Instead, Python tracks references to objects.
Two-part memory system
Example:
Python uses reference counting: when no variables point to an object, Python's garbage collector automatically frees it. This is efficient for most programs but can cause issues in circular references (which Python's cycle detector handles).
🎯 Why Understanding Python's Execution Matters
Real-world impact
🤖 How AI/ML Uses Python's Execution Model
When you train a machine learning model with PyTorch or TensorFlow, you write Python code that describes the computation graph. The interpreter compiles your Python to bytecode, and then the framework's C/CUDA backend (which you never see) executes the heavy math on GPU. You get Pythonic syntax with GPU speed. This is exactly why Python dominates AI—you describe what you want in simple code; the framework handles the fast execution. Understanding the three-stage execution (source → bytecode → runtime) helps you know where optimizations happen: in the framework's C/CUDA layers, not in your Python syntax.
🎯 Mini Challenge: Inspect the Bytecode
Open a Python terminal and run: python -c "import dis; dis.dis('x = 1 + 2')"
What you'll see: A list of bytecode instructions (LOAD_CONST, BINARY_ADD, STORE_NAME, etc.). Try to match each instruction to what it does in your calculation.
🎤 Interview Questions
.pyc files) and interprets that bytecode at runtime via the PVM. This is a hybrid approach. Unlike pure compiled languages (C), you don't manually run a compiler. Unlike pure interpreted languages (old shell scripts), Python caches the bytecode for speed..pyc works on any OS) but not human-readable. Python stores bytecode in __pycache__/module.cpython-.pyc files automatically. You rarely touch these files—Python manages them. If you delete them, Python regenerates them the next time you import or run the code.python script.py and it works—no compilation step. The interpreter does the compiling for you behind the scenes.torch.matmul(A, B), that's a Python function that immediately delegates to a C/CUDA function in the PyTorch backend. Your Python bytecode only handles the orchestration (loading data, setting hyperparameters, logging results)—the computation runs in compiled C or GPU kernels. This is why NumPy and PyTorch beat pure-Python loops by 100–1000x. You write Pythonic code but get C/GPU speed.🧠 Quick Quiz
📋 Python Execution Cheatsheet
| Stage | What Happens | Output/Format |
|---|---|---|
| 1. Source Code | You write .py file | Plain text, human-readable |
| 2. Compilation | Interpreter parses and translates | .pyc bytecode (cached) |
| 3. PVM Execution | Stack-based VM executes bytecode | Program output + side effects |
| GIL | Only one thread runs bytecode | Use multiprocessing for CPU parallelism |
| Memory | Automatic garbage collection | Reference counting, cycle detection |
| File Extension | .py is source | .pyc is bytecode (auto-cached) |
| Interpreters | CPython (most common), PyPy, Jython | All produce same bytecode |
| Portability | Same .pyc runs on any OS | No recompilation needed |
| Speed Trick | NumPy/PyTorch delegate to C/CUDA | Python syntax + compiled speed |
⚠️ Common Misconceptions
.pyc files are executables".pyc files are bytecode cache, not binaries. You can't run them directly. The PVM must be installed to execute them. They're just a speed optimization—Python regenerates them if deleted.multiprocessing only for CPU-bound work.✦ Key Takeaways
- Python compiles to bytecode automatically, then the PVM executes it line by line
- Bytecode is cached in
__pycache__/for speed; subsequent runs reuse it - Python is called "interpreted" because compilation is automatic and hidden, unlike C
- The PVM is stack-based: bytecode instructions push/pop values for computation
- The GIL limits multithreading to one thread executing bytecode at a time
- Python's memory is automatically garbage-collected via reference counting
- NumPy and PyTorch are fast because they call compiled C/CUDA code, not because Python is optimized
- Portability is a superpower: same
.py/.pycruns on Windows, Linux, Mac, and Raspberry Pi
From bytecode to production.
Build real AI projects.
Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst →