- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在 Python 字节码中跟踪 block 的目的是什么?
文档 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 中没有 block 作用域变量,所以这也是不喜欢的原因。
最佳答案
CPython 使用堆栈机器模型,其中临时值被压入值堆栈并由使用它们的指令弹出。当循环结束时,根据它结束的方式,它可能在值堆栈中留下不再需要的值。
帧的 block 堆栈跟踪循环开始时的值堆栈级别和一些其他构造,因此值堆栈可以恢复到循环/其他构造之后的代码需要堆栈所在的状态。 POP_BLOCK
是将堆栈恢复到 block 进入前状态的结构之一。
block 堆栈中的信息对于异常处理结构非常重要,因为当异常发生时,值堆栈可能处于各种奇怪的状态。循环不是必需的,我相信a patch进入 CPython 3.8 将消除循环的 block 堆栈条目,而不是让编译器静态地确定必要的处理。
关于python - 为什么 CPython 有一个 "POP_BLOCK"操作码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50259135/
在 Python 字节码中跟踪 block 的目的是什么? 文档 here提及: ... Per frame, there is a stack of blocks, denoting nested
我是一名优秀的程序员,十分优秀!