gpt4 book ai didi

python - 为什么 CPython 有一个 "POP_BLOCK"操作码?

转载 作者:太空狗 更新时间:2023-10-29 20:24:58 26 4
gpt4 key购买 nike

在 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_LOOPPOP_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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com