【发布时间】:2018-12-12 08:11:17
【问题描述】:
我无法理解此 Python 调试器会话中引发的以下异常:
(Pdb) p [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined
(Pdb) [move for move in move_values]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) max_value
0.5
(Pdb) (0.5, (0, 2))[0] == max_value
True
(Pdb) [move for move in move_values if move[0] == 0.5]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined
为什么有时告诉我 max_value 未定义而其他时候却没有?
顺便说一下,这是调试器启动之前的代码:
max_value = max(move_values)[0]
best_moves = [move for move in move_values if move[0] == max_value]
import pdb; pdb.set_trace()
我正在使用在 PyCharm 中运行的 Python 3.6。
修正更新:
经过更多测试后,当我在 iPython REPL 或 PyCharm 中执行以下操作时,在 pdb 会话中的列表解析中似乎看不到局部变量:
$ ipython
Python 3.6.5 | packaged by conda-forge | (default, Apr 6 2018, 13:44:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import pdb; pdb.set_trace()
--Call--
> /Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/IPython/core/displayhook.py(247)__call__()
-> def __call__(self, result=None):
(Pdb) x = 1; [x for i in range(3)]
*** NameError: name 'x' is not defined
但是在常规的 Python REPL 中它可以工作:
$ python
Python 3.6.5 | packaged by conda-forge | (default, Apr 6 2018, 13:44:09)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb; pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) x = 1; [x for i in range(3)]
[1, 1, 1]
我在上面测试了 3.4、3.5、3.6 版本,因此它似乎与版本无关。
更新 2
请注意,上面的测试('AMENDED UPDATE')是有问题的,因为它在交互式 REPL 中使用了import pdb; pdb.set_trace()。
另外,原来的问题不仅限于 iPython。
请参阅下面的answer by user2357112,以全面了解此处发生的情况。
很抱歉,如果我造成任何混乱!
【问题讨论】:
-
您可以尝试运行
globals()和locals()来查看您的作用域中定义了哪些变量吗? -
globals()和locals()的输出是 here -
我发现 this issue 从 2014 年开始在 Python 错误跟踪器中,状态为“已关闭”,解决方案“无法修复”,无论这意味着什么。
-
这听起来像是 iPython 和/或 Pycharm 与 Python 的接口中的一个错误。我会添加这些标签并删除名称错误。使用原始 Python 的另一个原因!
-
这个问题是在 2014 年 here 提出的,但似乎还没有解决方案......
标签: python ipython pdb nameerror