How Does a Python Code Run?

How Does a Python Code Run?

Have you ever wondered how human-readable .py files run on your computer? How does a computer understand instructions written with all those functions, lists, and other components?

In this blog post — just to make things fun and more memorable — we’ll explore how Python code is run through an analogy of a chef trying to cook a dish from a recipe written in a foreign language.

Before we dive in, it is important to note that unlike Python, a lot of programming languages like C++ and Java use compilers. Compilers convert the code written in their respective languages to machine-level binary, allowing any computer to run them.

However, Python takes a different approach involving an interpreter, bytecode, and PVM (Python Virtual Machine).

What is an Interpreter?

An interpreter works kind of like a compiler, but instead of converting the .py code into binary, it translates it to something called bytecode, which is saved as a .pyc file in the __pycache__ folder.

🧑‍🍳In our chef analogy:
We can think of an interpreter as a translator who converts the recipe from a foreign language to visuals, and those visuals as the bytecode. Visuals are not the final dish, but they are something the chef can work with.

What is a PVM (Python Virtual Machine)?

Since Bytecode is a language in between normal Python code and machine code, we need a special tool to execute it. This is where the Python Virtual Machine (PVM) comes in.

The PVM reads the bytecode and executes the written instructions line-by-line. It is responsible for executing loops, logic statements, etc. — all during runtime.

🧑‍🍳In our chef analogy:
The PVM is the chef who can understand the visual instructions (bytecode) and cook the dish as requested. The chef doesn’t involve with the original recipe (.py file) — they just follow the translated instructions.

Here is a diagram that sums up the whole process (with the analogy):

Diagram showing the Python code execution process with chef analogy

Comments

Popular Posts