Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to disassemble Python code

📅 2013-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ bytecode, dis, disassembler, python ⬩ 📚 Archive

Python code is compiled into Python bytecode, which is then executed on the Python virtual machine. Sometimes it is interesting to see what bytecode is produced from your Python code. Thankfully, Python ships with batteries included. So, it has a disassembler module built in that is called dis.

The dis method of the dis module can be easily used to disassemble a method in your Python code to its bytecode:

$ cat foo.py
def bar():
    a = 10
    b = 2
    c = a + b

$ python
>>> import dis
>>> import foo
>>> dis.dis(foo.bar)
  2           0 LOAD_CONST               1 (10)
              3 STORE_FAST               0 (a)

  3           6 LOAD_CONST               2 (2)
              9 STORE_FAST               1 (b)

  4          12 LOAD_FAST                0 (a)
             15 LOAD_FAST                1 (b)
             18 BINARY_ADD          
             19 STORE_FAST               2 (c)
             22 LOAD_CONST               0 (None)
             25 RETURN_VALUE

To see other methods of the dis module and information about the bytecode instructions, see dis in the Python documentation.

Tried with: Python 2.7.3 and Ubuntu 12.04 LTS


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧