gpt4 book ai didi

python-2.7 - Python 2 dis.dis() 无法解析包含 `for` 循环语法的字符串

转载 作者:行者123 更新时间:2023-12-04 22:25:41 26 4
gpt4 key购买 nike

使用 Python 3,dis.dis()适用于解析包含 for 循环语法的字符串:

>>> import dis
>>> dis.dis('for _ in range(10): pass')
1 0 SETUP_LOOP 20 (to 23)
3 LOAD_NAME 0 (range)
6 LOAD_CONST 0 (10)
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
12 GET_ITER
>> 13 FOR_ITER 6 (to 22)
16 STORE_NAME 1 (_)
19 JUMP_ABSOLUTE 13
>> 22 POP_BLOCK
>> 23 LOAD_CONST 1 (None)
26 RETURN_VALUE

在 Python 2 中,它产生了 string index out of range 错误:

In [30]: dis.dis('for _ in range(10): pass')
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-30-b7c7c1c77064> in <module>()
----> 1 dis.dis('for _ in range(10): pass')

/usr/lib/python2.7/dis.pyc in dis(x)
43 disassemble(x)
44 elif isinstance(x, str):
---> 45 disassemble_string(x)
46 else:
47 raise TypeError, \

/usr/lib/python2.7/dis.pyc in disassemble_string(code, lasti, varnames, names, constants)
110 def disassemble_string(code, lasti=-1, varnames=None, names=None,
111 constants=None):
--> 112 labels = findlabels(code)
113 n = len(code)
114 i = 0

/usr/lib/python2.7/dis.pyc in findlabels(code)
164 i = i+1
165 if op >= HAVE_ARGUMENT:
--> 166 oparg = ord(code[i]) + ord(code[i+1])*256
167 i = i+2
168 label = -1

IndexError: string index out of range

甚至将 for 循环包装在函数中以实现常规语法也无济于事:

def test():
for _ in range(10):
pass

dis.dis('test')
<The same error>

这是错误还是其他地方记录的期望行为?

软件版本

$ python2 -V
Python 2.7.9

$ python3 -V
Python 3.4.2

$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=debian
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support/"
BUG_REPORT_URL="https://bugs.debian.org/"

最佳答案

Python 2 的 dis.dis 不接受包含 Python 代码的字符串作为参数,它接受包含字节码 或函数的字符串。

你最好的选择是这样的:

>>> def test():
... for _ in range(10):
... pass
...
>>>
>>> import dis
>>> dis.dis(test)
2 0 SETUP_LOOP 20 (to 23)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (10)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 6 (to 22)
16 STORE_FAST 0 (_)

3 19 JUMP_ABSOLUTE 13
>> 22 POP_BLOCK
>> 23 LOAD_CONST 0 (None)
26 RETURN_VALUE

关于python-2.7 - Python 2 dis.dis() 无法解析包含 `for` 循环语法的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32469963/

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