Skip to content

🛠 Python Disassembler

This tip is for you who like to bit diddling and understand what python does under the hood.

Python has a module that disassembles your code, that is, you can analyze the bytecode of your code!

⚗️ Test

Let's test it, for that we need to import the module called dis and use it as shown in the example below::

# >>>$ from dis import dis
# >>>$ 
# >>>$ 
# >>>$ def add_two(number: int) -> int:
# ...$     return number + 2
# >>>$ 
# >>>$ dis(add_two)

  2           0 LOAD_FAST                0 (number)
              2 LOAD_CONST               1 (2)
              4 BINARY_ADD
              6 RETURN_VALUE

🔎 Explaining the result

dis_example.py
from dis import dis # (1)


def add_two(number: int) -> int: # (2)
    return number + 2


dis(add_two) # (3)

# Result
#  2           0 LOAD_FAST                0 (number) (4)
#              2 LOAD_CONST               1 (.2.) (5)
#              4 BINARY_ADD (6)
#              6 RETURN_VALUE (7)
  1. Importing dis library.
  2. Declare a function that adds two to a number.
  3. Calling Disassembly function to show us the bytecode.
  4. Pushes a reference to the local co_varnames[var_num] onto the stack. Doc Link
  5. Pushes co_consts[consti] onto the stack. Doc Link
  6. Implements TOS = TOS1 + TOS. Doc Link
  7. Returns with TOS to the caller of the function. Doc Link

📖 Official Documentation

Comments