How Python Works Internally: Bytecode, PVM, CPython

Python tutorial · PySpark.in

Python works internally in four steps: your source code is tokenized, parsed into an abstract syntax tree (AST), compiled to bytecode, and executed by the Python Virtual Machine (PVM) inside CPython. So Python is both compiled and interpreted. This guide walks through each step with code you can run.

Python is often praised for its simplicity: you write a few lines of code, run it, and it just works. But have you ever wondered what happens in the backend when you run Python code?

Behind its beginner-friendly syntax, Python has a powerful internal mechanism that involves parsing, compiling, interpreting, and execution. Understanding this flow helps developers write efficient code and appreciate the language’s design.

The Lifecycle of a Python Program

When you run a Python file (say, python myscript.py), here’s what happens step by step:

1. Source Code (.py file)

Your human-readable code is written in a .py file, for example:

print("Hello, Python!")

2. Lexical Analysis (Tokenization)

Python first reads the source code and breaks it down into small pieces called tokens (keywords, identifiers, operators, etc.).
Example:

print("Hello, Python!")

gets tokenized into:

3. Parsing

The tokens are then arranged into a Parse Tree (or Abstract Syntax Tree – AST) that represents the grammatical structure of your code.

For example, print("Hello, Python!") becomes an AST node representing a function call with a string argument.

4. Compilation to Bytecode

Next, Python converts the AST into bytecode, which is a low-level set of instructions understood by the Python interpreter.

This bytecode is stored in .pyc files (inside the __pycache__ folder). For example, when you import mymodule, CPython 3.12 caches it as __pycache__/mymodule.cpython-312.pyc and reuses it next time if the source has not changed. The script you run directly (python myscript.py) is compiled in memory every time and is not cached.

Bytecode is platform-independent: the same .pyc works on Windows, Linux or macOS. It is tied to the Python version, though, so a .pyc written by 3.12 is ignored and rebuilt by 3.13.

5. Python Virtual Machine (PVM)

The bytecode is then fed into the Python Virtual Machine (PVM), which is essentially the interpreter loop. The PVM executes each bytecode instruction one by one.

See each step yourself

The standard library exposes every stage. Run these blocks to see the tokens and AST for print("Hello, Python!"), then the bytecode of a small function (the exact instructions depend on your Python version):

```

import ast, io, tokenize

 

src = 'print("Hello, Python!")'

 

# Step 2: tokens

for tok in tokenize.generate_tokens(io.StringIO(src).readline):

if tok.string.strip():

print(tokenize.tok_name[tok.type], repr(tok.string))

 

# Step 3: the abstract syntax tree

print(ast.dump(ast.parse(src).body[0], indent=2))

```

```

import dis

 

def add(a, b):

return a + b

 

# Step 4: the bytecode the PVM will execute

dis.dis(add)

 

# compile() runs the same compiler; 2 + 3 is already folded to 5

code = compile("x = 2 + 3\nprint(x)", "demo.py", "exec")

print(code.co_consts)

exec(code) # Step 5: the PVM runs it

```

Is Python compiled or interpreted?

Both. CPython first compiles your source to bytecode, then the PVM interprets that bytecode. What Python does not do by default is compile to machine code ahead of time, as C or Go do, which is why it is usually described as an interpreted language. PyPy adds a just-in-time (JIT) compiler that turns hot bytecode into machine code, and CPython 3.13 ships an experimental JIT that is off by default.

The Role of CPython, PyPy, and Others

When people say “Python,” they usually mean CPython, the default implementation written in C. CPython handles all the steps above.

Other implementations exist:

Each implementation has its own way of handling bytecode and execution, but the overall workflow remains similar.

Memory Management in Python

Python also manages memory in the backend using:

  1. Private Heap → All Python objects and data structures are stored in a private heap.

  2. Memory Manager → Allocates and releases memory automatically.

  3. Garbage Collector → Removes unused objects using reference counting and a cyclic garbage collector.

This is why developers rarely worry about memory allocation in Python—it’s all automated.

You can watch reference counting and the cyclic collector at work:

```

import gc, importlib.util, sys

 

# Where CPython caches the bytecode of an imported module

print(importlib.util.cache_from_source("mymodule.py"))

 

# Reference counting: each name and argument holding the object adds one

data = []

print("references:", sys.getrefcount(data))

 

# Two lists that point at each other never reach zero references:

# the cyclic garbage collector frees them

a, b = [], []

a.append(b)

b.append(a)

del a, b

print("unreachable objects collected:", gc.collect())

```

The GIL: why one process runs one bytecode at a time

CPython has a Global Interpreter Lock (GIL): only one thread executes Python bytecode at a time in a process. It keeps reference counting safe without locking every object. Threads still help with I/O, because the GIL is released while a thread waits on the network or disk, but CPU-heavy work needs multiprocessing, C extensions such as NumPy that release the GIL, or a distributed engine such as PySpark. Python 3.13 also offers an experimental free-threaded build without the GIL.

Putting It All Together

Here’s a simplified diagram of how Python works:

Your Code (.py) → Tokens → AST → Bytecode (.pyc) → PVM → Output

Example with print("Hello, Python!"):

  1. Code written → print("Hello, Python!")

  2. Tokenized → ['print', '(', 'Hello, Python!', ')']

  3. Parsed → Function call node in AST

  4. Compiled → Bytecode instructions (LOAD_NAME, LOAD_CONST, CALL; exact names vary by Python version)

  5. Executed → PVM runs → Output: Hello, Python!

Why Should You Care About Python Internals?

Conclusion

Python may look simple on the surface, but behind the scenes it follows a well-defined process: source code → tokens → AST → bytecode → PVM execution. This combination of compilation and interpretation is what makes Python flexible and powerful.

FAQ: how Python works internally

What is the PVM in Python? The Python Virtual Machine is the loop inside the interpreter that reads bytecode instructions and executes them one by one. In CPython it is written in C.

What is CPython? The reference implementation of Python, written in C, that you download from python.org. It contains the compiler, the PVM, the memory manager and the standard library.

Where are .pyc files stored? In a __pycache__ folder next to the module, named with the interpreter and version, for example mymodule.cpython-312.pyc. They are created when a module is imported, not for the script you run.

Why is Python slower than C? The PVM interprets bytecode at run time and every value is a full object with a type check, while C is compiled ahead of time to machine code. Libraries such as NumPy and PySpark move the heavy work into compiled code.

Keep learning Python

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges