类型错误:'NoneType'对象不可迭代

211 投票
12 回答
1032869 浏览
提问于 2025-04-16 05:11

什么是 TypeError: 'NoneType' 对象不可迭代 的意思?举个例子:

for row in data:  # Gives TypeError!
    print(row)

12 个回答

64

代码:for row in data:
错误信息:TypeError: 'NoneType' object is not iterable

这个错误是指哪个对象呢?有两个可能,rowdata。在for row in data这行代码中,哪个需要是可以遍历的呢?只有data

data有什么问题呢?它的类型是NoneType。只有None这个值的类型是NoneType。所以可以说data是None

你可以在一个开发环境中验证这一点,或者在for语句之前插入例如print "data is", repr(data),然后重新运行代码。

想想接下来你需要做什么: “没有数据”应该怎么表示呢?我们是写一个空文件?抑或是抛出一个异常,记录一个警告,还是保持沉默呢?

119

错误解释:'NoneType'对象不可迭代

在Python2中,NoneType是表示None的类型。在Python3中,NoneType是None的类,比如:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

当一个变量的值是None时,迭代会失败:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

如果Python方法没有返回值,它们会返回NoneType:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

你需要像这样检查你的循环结构是否为NoneType:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido建议只用is来检查None,因为is在身份检查上更可靠。不要使用相等操作,因为那样可能会引发其他问题。Python的编码风格指南 - PEP-008

NoneType很狡猾,可能会从lambda中混入:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType不是一个有效的关键字:

a = NoneType     #NameError: name 'NoneType' is not defined

None和字符串连接:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

这里发生了什么?

Python的解释器把你的代码转换成了pyc字节码。Python虚拟机处理这个字节码时,遇到了一个循环结构,要求迭代一个包含None的变量。这个操作是通过调用None的__iter__方法来完成的。

但是None并没有定义__iter__方法,所以Python虚拟机告诉你它看到的情况:NoneType没有__iter__方法。

这就是为什么Python的鸭子类型理念被认为是有问题的。程序员对一个变量做了完全合理的操作,但在运行时却被None污染了,Python虚拟机试图继续运行,结果却出现了一堆无关的错误。

Java或C++没有这些问题,因为这样的程序是无法编译的,因为你没有定义当出现None时该怎么做。Python给程序员留了很多余地,允许你做一些在特殊情况下不应该期望能正常工作的事情。Python就像一个随声附和的人,明明应该阻止你自我伤害,却在说“好的,先生”。而Java和C++则会更严格地保护你。

265

这句话的意思是,data的值是None

撰写回答