Introduction to Python dis Module

Posted by Afsal on 20-Sep-2024

Hi Pythonistas!

One of the previous posts we have discussed about how python works?. Today we are digging a little bit more about working. In Python, your source code goes through a compilation process that converts it into bytecode, which the Python Virtual Machine (PVM) then executes. Understanding this bytecode can give you valuable insights into how your Python code actually runs.

The Python dis module helps you inspect this bytecode by disassembling Python code into human-readable instructions. In this post, we’ll explore the basics of the dis module and how to use it.

What is Bytecode?

Bytecode is a low-level, platform-independent set of instructions that the Python interpreter executes. When Python compiles your code, it translates it into bytecode that the PVM can interpret and run. This bytecode is stored in .pyc files, located in the __pycache__ directory.

The dis Module

The dis module is part of Python's standard library, and it allows you to inspect the bytecode generated from your Python code. This is particularly helpful for performance analysis, debugging, and gaining a deeper understanding of Python internals.

Disassembling a Simple Function

Let’s take a look at a basic Python function and use the dis module to inspect its bytecode:

import dis

def add(a, b):
    return a + b

dis.dis(add)

Output:

  4       0 LOAD_FAST            0 (a)

           2 LOAD_FAST            1 (b)

           4 BINARY_ADD

           6 RETURN_VALUE

This output shows the bytecode generated for the add function. Here’s what the instructions mean:

LOAD_FAST 0 (a): Load the local variable a onto the stack.

LOAD_FAST 1 (b): Load the local variable b onto the stack.

BINARY_ADD: Perform the addition (a + b).

RETURN_VALUE: Return the result of the addition from the function.

You can refer to all the byte code from this documentation. In the upcoming post we will learn more about this. Please share your valuable suggestions with afsal@parseltongue.co.in