python

More On Python Bytecode

Python Bytecode is a code which python virtual runtime reads and provides the output.

NOTE :-  It’s just for understanding compilation. Detailed programming we will write soon.

When we write a code we can see the bytecode using dis module. Dis module is used to Disassembling bytecode – means taking the bytes and printing out something we humans can understand as below,

>>> def fib():

print “h”

>>> dis.dis(fib)

2           0 LOAD_CONST               1 (‘h’)

3 PRINT_ITEM

4 PRINT_NEWLINE

5 LOAD_CONST               0 (None)

8 RETURN_VALUE

>>> def fib1():

print “r”

print “t”

>>> dis.dis(fib1)

2           0 LOAD_CONST               1 (‘r’)

3 PRINT_ITEM

4 PRINT_NEWLINE

3           5 LOAD_CONST               2 (‘t’)

8 PRINT_ITEM

9 PRINT_NEWLINE

10 LOAD_CONST               0 (None)

13 RETURN_VALUE

>>> def fib2():

print “y”

print “f”

print “j”

>>> dis.dis(fib2)

2           0 LOAD_CONST               1 (‘y’)

3 PRINT_ITEM

4 PRINT_NEWLINE

3           5 LOAD_CONST               2 (‘f’)

8 PRINT_ITEM

9 PRINT_NEWLINE

4          10 LOAD_CONST               3 (‘j’)

13 PRINT_ITEM

14 PRINT_NEWLINE

15 LOAD_CONST               0 (None)

18 RETURN_VALUE

When we see the above 3 examples after executing dis.dis(fib), left side it is printing line number and right side bytecode specific instruction LOAD_CONST and it will load 1(‘h’) then PRINT_ITEM  followed by PRINT_NEWLINE.  If you see three examples carefully, it is loading constant and printing item. When LOAD_CONST   becomes 0, it returned the value RETURN_VALUE.

To get raw bytecode run func_code.co_code on function name as below and to get constants run func_code.co_consts[1] on function name as below and to print bytecode use ord(var) on funcname.func_code.co_code

>>> code = fib.func_code.co_code
>>> code
‘d\x01\x00GHd\x00\x00S’

>>> fib.func_code.co_consts[1]
‘h’
>>>

>> [ord(b) for b in fib.func_code.co_code]
[100, 1, 0, 71, 72, 100, 0, 0, 83]
>>>

This is the bytecode which is executed by Python Virtual Machine and can be disassembled by dis module for human readable purpose.

You can explore more on the same, please Link1Link2 for more information on the same

 

 

Leave a Reply