Python字节码中“>>”的含义

Meaning of '>>' in Python byte code

我反汇编了以下python代码

def factorial(n):
    if n <= 1:
        return 1
    elif n == 2:
        return 2
    elif n ==4:
        print('hi')
    return n * 2

和生成的字节码

 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        

上述字节码中的“>>”符号代表什么?

它们是跳跃目标;位置较早 *JUMP* 字节码在满足条件时跳转到。

第一跳:

         9 POP_JUMP_IF_FALSE       16

跳转到偏移量 16,因此在偏移量 16 处输出有一个目标 >>:

4     >> 16 LOAD_FAST                0 (n)

来自 dis.disassemble() function docs 名称的每一列:

[...]

  1. a labelled instruction, indicated with >>,

dis.findlabels() function:

Detect all offsets in the code object code which are jump targets, and return a list of these offsets.