首页 > 解决方案 > 在 Pycharm 调试器中迭代字典时找不到局部变量

问题描述

嗨,我有以下示例,

class Dummy:
    def __init__(self, id):
        self.id = id

    def __hash__(self):
        return hash(self.id)

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__.__eq__(other.__dict__)


d1 = Dummy(1)
d2 = Dummy(2)
d = {d1: None, d2: None}

for k, v in d.items():
    print([w.id for w in d.keys() if w.id != k.id])

当我在 Pycharm 中运行上述代码时,当我在 for 循环行添加断点时失败,但如果我让代码运行完成,则成功。

在调试器中:

import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.6.7 | packaged by conda-forge | (default, Feb 28 2019, 02:16:08) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin

>>> for k, v in d.items():
        print([w.id for w in d.keys() if w.id != k.id])

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<string>", line 2, in <module>
  File "<string>", line 2, in <listcomp>
NameError: name 'k' is not defined

当我没有断点运行时:

/anaconda3/envs/example/bin/python example.py
[2]
[1]

Process finished with exit code 0

我不确定这是预期的行为还是环境问题。

调试器故障图像供参考: 在此处输入图像描述

标签: pythonpycharm

解决方案


推荐阅读