How Does Python Actually Work?

What is an interpreted language? Is python interpreted? What is an interpreter? How is it different than compiled language? Why is compiled language faster?

Manisha Naidu
ILLUMINATION
3 min readOct 13, 2021

--

Photo by Annie Spratt on Unsplash

There are so many questions around this and its really not complicated if you understand a simple flow of how different program runs. And that is what I would like to discuss today- a simple explanation of how a program works in our computer.

First of all, let us see how C, C++ works. As you know these are compiled languages, and that just means that our source code is directly translated to a format which the processors can execute, this is what is called as machine code which is in binary format.

So when you have a source code saved in your system, it is basically a text file stored in a hard disk.

And when you run the command,

gcc -o program source.cpp

It gets compiled to machine code by a compiler, in this case gcc.

The machine code generated by the compiler is stored in memory, which is where processor looks for the instructions to execute. It fetches each instruction and starts executing.

working of a compiled language

This step of compiling is called as “build” and you have to build your code manually every time you make a change in the source.

C, C++, Go, Erlang, all of these are compiled languages.

So now what’s the deal with python and it being interpreted language?

When you run, python source.py

Here python is the interpretor, which is also a binary and this binary is what gets loaded into the memory, not the source code.

Interpreter has two components-

  1. Compiler
  2. PVM

The compiler in the interpreter takes the source code and translates to byte code.

Note that it is byte code and not machine code. Processors don’t understand byte code, it only understands machine code. And this is where PVM comes into picture.

PVM is a python virtual machine similar to JVM for Java, this PVM understands the byte code.

It takes this byte code and executes on the hardware.

Working of python

Now do you understand why Python is considered to be slower?
It’s because of translating the code at runtime, which creates additional overhead. But with Just-in-time compilation being developed, this slowness is reducing.

To see only the compiled code (byte code) and not run the program:

python3 -m py_compile source.py

It stores the byte code in pycache folder, which has .pyc file

For human readable format, use the below command instead:

python3 -m dis source.py

Hope you are now clear about the working of interpreted and compiled languages and understand the difference between both.

If you want to support my work,

https://www.buymeacoffee.com/manishanaidu

--

--

Manisha Naidu
ILLUMINATION

Software Engineer at Intel, zealous coder | keep learning, keep developing!