How to disassemble Python code

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
def bar():
a = 10
b = 2
c = a + b
$ python
>>> import dis
>>> import foo
>>> dis.dis(
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)
19 STORE_FAST 2 (c)
22 LOAD_CONST 0 (None)

view raw
hosted with ❤ by GitHub

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.