EP 3: How Python Works Internally (The Python Virtual Machine)
This lecture breaks down the internal "translation" process of Python. It explains that while Python is called an "Interpreted" language, it actually goes through a compilation phase to create Bytecode. The session focuses on the roles of the Source Code, the Compiler, Bytecode, and the Python Virtual Machine (PVM).
1. The Python Execution Process
When you run a Python program (e.g., test.py), it doesn't talk to the computer hardware immediately. It follows these four critical steps:
-
Source Code (.py): This is the high-level code you write (like
print("Hello")). -
The Compiler: Unlike C++, Python has an internal compiler that first checks for syntax errors. If the code is correct, it translates it.
-
Bytecode (.pyc): The compiler generates an intermediate, low-level representation called "Bytecode."
-
Note: You may see a folder named
__pycache__in your directory; this is where Python stores this bytecode to make future executions faster.
-
-
Python Virtual Machine (PVM): This is the "Engine" of Python. It reads the Bytecode and converts it into Machine Code (0s and 1s) that your specific CPU can understand.
2. What is Bytecode?
-
Platform Independence: Bytecode is the reason Python is "Platform Independent." The same bytecode can run on Windows, Mac, or Linux, as long as that system has a PVM installed.
-
Not Machine Code: Bytecode is not understandable by the CPU; it is only understandable by the PVM.
3. The Role of the PVM (Python Virtual Machine)
The PVM is the most important component of the Python software.
-
It is an interpreter that scans the bytecode line-by-line.
-
If an error occurs during this stage (like a ZeroDivisionError), it is called a Runtime Error.
-
The PVM is what makes Python slightly slower than C, because it has to interpret code every time the program runs.
4. Key Differences: Compiler vs. Interpreter in Python
The lecture clarifies a common confusion: "Is Python Compiled or Interpreted?"
-
The Answer: It is Both.
-
The Compilation part happens first (Source Code $\rightarrow$ Bytecode).
-
The Interpretation part happens last (Bytecode $\rightarrow$ Machine Code via PVM).
5. Flavors of Python
The video briefly mentions that there are different "flavors" of Python depending on how they are implemented:
-
CPython: The standard version (written in C).
-
JPython (Jython): Designed to run on the Java platform.
-
IronPython: Designed for the .NET framework.
-
PyPy: A version focused on high performance and speed.
What's Your Reaction?