I have disassembled the following python code
def factorial(n):
if n <= 1:
return 1
elif n == 2:
return 2
elif n ==4:
print('hi')
return n * 2
and the resulting bytecode
2 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (1)
6 COMPARE_OP 1 (<=)
9 POP_JUMP_IF_FALSE 16
3 12 LOAD_CONST 1 (1)
15 RETURN_VALUE
4 >> 16 LOAD_FAST 0 (n)
19 LOAD_CONST 2 (2)
22 COMPARE_OP 2 (==)
25 POP_JUMP_IF_FALSE 32
5 28 LOAD_CONST 2 (2)
31 RETURN_VALUE
6 >> 32 LOAD_FAST 0 (n)
35 LOAD_CONST 3 (4)
38 COMPARE_OP 2 (==)
41 POP_JUMP_IF_FALSE 52
7 44 LOAD_CONST 4 ('hi')
47 PRINT_ITEM
48 PRINT_NEWLINE
49 JUMP_FORWARD 0 (to 52)
8 >> 52 LOAD_FAST 0 (n)
55 LOAD_CONST 2 (2)
58 BINARY_MULTIPLY
59 RETURN_VALUE
What do the '>>' symbols in the above bytecode stand for?
The bytecode is a low-level platform-independent representation of your source code, however, it is not the binary machine code and cannot be run by the target machine directly. In fact, it is a set of instructions for a virtual machine which is called the Python Virtual Machine (PVM).
Bytecode is an intermediate language for the Python virtual machine that's used as a performance optimization.
In most computer systems, a byte is a unit of data that is eight binary digits long. A byte is the unit most computers use to represent a character such as a letter, number or typographic symbol. Each byte can hold a string of bits that need to be used in a larger unit for application purposes.
An example of bytecode One of the most common examples of bytecode in action is the Java programming language. When an application is written in Java, the Java compiler converts the source code to bytecode, outputting the bytecode to a CLASS file.
They are jump targets; positions earlier *JUMP*
bytecode jumps to when the condition is met.
The first jump:
9 POP_JUMP_IF_FALSE 16
jumps to offset 16, so at offset 16 the output has a target >>
:
4 >> 16 LOAD_FAST 0 (n)
From the dis.disassemble()
function docs names each column:
[...]
- a labelled instruction, indicated with
>>
,
and the dis.findlabels()
function:
Detect all offsets in the code object code which are jump targets, and return a list of these offsets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With