10min python: dis assembler

10min python: dis

what is dis?

dis is the disassembler. It shows to you how the python interpreter executes your python code in human readable format.

why do we need it?

To understand and optimise your python code to make it easier to the world.

how it works?

There is an inbuild module called dis which has the job and does it.It just reads the compiler understandable code(means byte code) and converting into mneumonics which is the cpu understandable language.

def your-function():
    pass

>>>dis.dis(your-function)

example:

In [3]: import dis

In [4]: help(dis)

In [5]: def show_mybytes(a, b):
   ...:     l = []
   ...:     l.append(a)
   ...:     l.append(b)
   ...:     c = a + b
   ...:     l.append(c)
   ...:     return l
   ...: 

In [6]: show_mybytes(4,5)
Out[6]: [4, 5, 9]

output:


In [8]: dis.dis(show_mybytes)
  2           0 BUILD_LIST               0
              3 STORE_FAST               2 (l)

  3           6 LOAD_FAST                2 (l)
              9 LOAD_ATTR                0 (append)
             12 LOAD_FAST                0 (a)
             15 CALL_FUNCTION            1
             18 POP_TOP             

  4          19 LOAD_FAST                2 (l)
             22 LOAD_ATTR                0 (append)
             25 LOAD_FAST                1 (b)
             28 CALL_FUNCTION            1
             31 POP_TOP             

  5          32 LOAD_FAST                0 (a)
             35 LOAD_FAST                1 (b)
             38 BINARY_ADD          
             39 STORE_FAST               3 (c)

  6          42 LOAD_FAST                2 (l)
             45 LOAD_ATTR                0 (append)
             48 LOAD_FAST                3 (c)
             51 CALL_FUNCTION            1
             54 POP_TOP             

  7          55 LOAD_FAST                2 (l)
             58 RETURN_VALUE        

In [9]: 

in this above example, first column is line no of our python code statements.Second column is the neumonic instraction address position(I think but not sure), third column is the mneumonic instructions for the cpu, last column is human understanble format mapping between python code to assembly code

Advertisements

About Navaneethan

mixed feelings...
This entry was posted in 10min, Python and tagged , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s