Python 'if x is None' 未捕获 NoneType

标签 python python-2.7

下面的代码片段不断返回“NoneType 不可迭代”错误。为什么 if 语句没有捕获到这一点?

inset = set()
for x in node.contacted:
    print type(x)
    if x.is_converted() is True:
        nset.add(x)
        if x.contacted is None:
            memotable[node.gen][node.genind] = nset
        else:
            nset.union(self.legacy(x, memotable))
            memotable[node.gen][node.genind] = nset

根据要求进行完整回溯:

Traceback (most recent call last):

File "F:\Dropbox\CS\a4\skeleton\trialtest.py", line 142, in test_legacy_and_frac()

File "F:\Dropbox\CS\a4\skeleton\trialtest.py", line 125, in test_legacy_and_frac cunittest2.assert_equals(set([n10,n12,n21]), t.legacy(n00,mtable))

File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy nset.union(self.legacy(x, memotable))

File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy nset.union(self.legacy(x, memotable))

TypeError: 'NoneType' object is not iterable

最佳答案

if声明保证 x.contacted不是“无”。

但是x.contacted不是您要迭代或索引的内容,因此它不会保护任何内容。

没有理由memotablememotable[node.gen]不可能None即使x.contacted是别的东西。就此而言,我们不知道self.legacy(x, memotable)里面的代码是什么。确实如此——也许它尝试迭代 x ,或other_table[x] ,或者谁知道什么,其中任何一个都可能是 None .

这就是为什么您需要查看整个回溯,而不仅仅是错误字符串。它会准确地告诉您哪个语句失败以及原因。


现在您已经粘贴了回溯:

File "F:\Dropbox\CS\a4\skeleton\trial.py", line 138, in legacy nset.union(self.legacy(x, memotable))

是的,这就是 self.legacy 内部发生的事情。线,它与x.contacted完全无关。 。问题几乎可以肯定是你的 self.legacy方法正在返回 None ,所以你正在做 nset.union(None) .

再说一次,是否 x.contacted是或不是None在这里完全不相关,所以你的支票不会在这里保护你。

如果您希望我们调试该函数中的问题,您必须向我们提供该函数的代码,而不是与错误无关的代码。也许这是一些愚蠢的事情,比如做 a + b而不是return a + b最后,或者可能是一些深层的逻辑错误,但我们确实无法猜测。

关于Python 'if x is None' 未捕获 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771888/

相关文章:

python - 回文发生器

python - 使用 beautiful soup 从标签中提取 'href'

python - 符号 `%` 的抽象概念名称

python - 使用 Django 将文件发送到 GCS 的最佳方式

python - Tensorflow 磁贴抛出 TypeError : List of Tensors when single Tensor expected

Python仅列出包含特定子文件夹的文件夹

python - 如何在不阻止python执行的情况下在python中启动可执行文件

python - 如何将Python中的内容抓取到Excel中

python - DJANGO_SETTINGS_MODULE 未定义

Python:如何将字符串解析为递归字典