在
Python字节码中跟踪块的目的是什么?
文档here提到:
… Per frame, there is a stack of blocks, denoting nested loops, try statements, and such.
但实际上它们似乎并不需要实际执行循环.例如,玩弄REPL我看到:
>>> def foo():
... while True:
... print('hi')
...
>>> for inst in list(dis.get_instructions(foo)): print(inst)
...
Instruction(opname='SETUP_LOOP', opcode=120, arg=12, argval=14, argrepr='to 14', offset=0, starts_line=2, is_jump_target=False)
Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='print', argrepr='print', offset=2, starts_line=3, is_jump_target=True)
Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval='hi', argrepr="'hi'", offset=4, starts_line=None, is_jump_target=False)
Instruction(opname='CALL_FUNCTION', opcode=131, arg=1, argval=1, argrepr='', offset=6, starts_line=None, is_jump_target=False)
Instruction(opname='POP_TOP', opcode=1, arg=None, argval=None, argrepr='', offset=8, starts_line=None, is_jump_target=False)
Instruction(opname='JUMP_ABSOLUTE', opcode=113, arg=2, argval=2, argrepr='', offset=10, starts_line=None, is_jump_target=False)
Instruction(opname='POP_BLOCK', opcode=87, arg=None, argval=None, argrepr='', offset=12, starts_line=None, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=0, argval=None, argrepr='None', offset=14, starts_line=None, is_jump_target=True)
Instruction(opname='RETURN_VALUE', opcode=83, arg=None, argval=None, argrepr='', offset=16, starts_line=None, is_jump_target=False)
列出的JUMP_ABSOLUTE指令跳转到列出的LOAD_GLOBAL指令.从查看说明看起来,似乎SETUP_LOOP和POP_BLOCK操作码可能是无操作.
根据我的理解,在Python中没有块范围的变量,因此不喜欢它也是原因.