gpt4 book ai didi

python - 列出来自 Python 调试器的理解范围错误

转载 作者:太空狗 更新时间:2023-10-30 01:38:00 25 4
gpt4 key购买 nike

在调试我的代码时,我想使用列表理解。但是,当我在函数内部时,似乎无法从调试器评估列表理解。

我正在使用 Python 3.4。

脚本内容:

$ cat test.py 
#!/usr/bin/python

def foo():
x = [1, 2, 3, 3, 4]

print(x)

foo()

交互式调试:

$ python3 -mpdb test.py                                                                                                                                           
> /tmp/test.py(3)<module>()
-> def foo():
(Pdb) step
> /tmp/test.py(8)<module>()
-> foo()
(Pdb)
--Call--
> /tmp/test.py(3)foo()
-> def foo():
(Pdb)
> /tmp/test.py(4)foo()
-> x = [1, 2, 3, 3, 4]
(Pdb)
> /tmp/test.py(6)foo()
-> print(x)
(Pdb) p [x for _ in range(1)]
*** NameError: name 'x' is not defined
(Pdb) p x
[1, 2, 3, 3, 4]

为什么 x 对列表理解是未知的?我如何评估调试器的列表理解或实现等效行为?这是一个错误,还是对调试器的某种基本限制?

最佳答案

在 Python 3 中,由于推导式的实现方式发生了变化,您必须先在 pdb 中使用 interact 命令才能访问任何非全局变量。

>>> def foo(): [][0]
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in foo
IndexError: list index out of range
>>> import pdb;pdb.pm()
> <stdin>(1)foo()
(Pdb) x = 4
(Pdb) [x for _ in range(2)]
*** NameError: name 'x' is not defined
(Pdb) interact
*interactive*
>>> [x for _ in range(2)]
[4, 4]
>>>

关于python - 列出来自 Python 调试器的理解范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666389/

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