类型错误:“NoneType”对象不可迭代
- 2025-02-10 08:56:00
- admin 原创
- 76
问题描述:
是什么意思?例如:TypeError: 'NoneType' object is not iterable
for row in data: # Gives TypeError!
print(row)
解决方案 1:
意思是 的值data
是None
。
解决方案 2:
错误解释:“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
NoneTypes 很狡猾,可以从 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 的变量进行迭代。该操作是通过调用__iter__
None 上的方法执行的。
None 没有__iter__
定义方法,所以 Python 的虚拟机会告诉您它所看到的内容:NoneType 没有__iter__
方法。
这就是Python 的鸭子类型思想被认为不好的原因。程序员对变量做了一些完全合理的事情,但在运行时,它被 None 污染了,Python 虚拟机试图继续前进,结果吐出了一堆不相关的废话。
Java 或 C++ 不会出现这些问题,因为这样的程序无法通过编译,因为您没有定义当 None 出现时该做什么。Python 允许程序员做很多在特殊情况下不可能完成的事情,这给了程序员很多上吊的机会。Python 是一个唯唯诺诺的人,当它想阻止你伤害自己时,它就会说“是的先生”,就像 Java 和 C++ 一样。
解决方案 3:
代码:for row in data:
错误信息:TypeError: 'NoneType' object is not iterable
它抱怨的是哪个对象?两个选项,row
和data
。在中for row in data
,哪个需要可迭代?只有data
。
有什么问题data
? 它的类型是NoneType
。 只有None
类型NoneType
。 所以data is None
。
您可以在 IDE 中验证这一点,或者通过在语句print "data is", repr(data)
前插入例如for
,然后重新运行。
想想接下来你需要做什么:
应该如何表示“没有数据”?我们要写一个空文件吗?我们要抛出异常、记录警告还是保持沉默?
解决方案 4:
另一种可能产生此错误的情况是,当您将某些东西设置为与函数返回的值相等,但忘记实际返回任何内容时。
例子:
def foo(dict_of_dicts):
for key, row in dict_of_dicts.items():
for key, inner_row in row.items():
Do SomeThing
#Whoops, forgot to return all my stuff
return1, return2, return3 = foo(dict_of_dicts)
这是一个有点难以发现的错误,因为如果行变量在某次迭代中恰好为 None,也会产生该错误。发现该错误的方法是跟踪在最后一行失败,而不是在函数内部失败。
如果你只从函数返回一个变量,我不确定是否会产生错误...我怀疑错误“'NoneType'对象在 Python 中不可迭代”在这种情况下实际上意味着“嘿,我正在尝试迭代返回值以按顺序将它们分配给这三个变量,但我只得到 None 来迭代”
解决方案 5:
这意味着数据变量传递的是 None (类型为 NoneType),相当于nothing。因此,它不能像您尝试的那样作为列表进行迭代。
解决方案 6:
您正在使用如下参数调用 write_file:
write_file(foo, bar)
但是您没有正确定义“foo”,或者您的代码中有一个拼写错误,因此它会创建一个新的空变量并将其传入。
解决方案 7:
它的意思是data
is None
,它不是可迭代的。添加or []
* 可防止出现异常,并且不会打印任何内容:
for row in data or []: # no more TypeError!
print(row)
*感谢一些早期的评论;请注意,引发异常也可能是一种期望的行为和/或不当设置的指标data
。
解决方案 8:
对我来说,这是一个戴上Groovy 帽子而不是 Python 3 帽子的情况。
忘记了函数return
末尾的关键字def
。
几个月来一直没有认真编写 Python 3 代码。我以为例程中评估的最后一个语句是按照 Groovy(或 Rust)方式返回的。
经过几次迭代,查看堆栈跟踪,插入try: ... except TypeError: ...
块调试/单步执行代码来找出问题所在。
该消息的解决方案当然没有让我注意到错误。
解决方案 9:
这也取决于你使用的 Python 版本。在 Python 3.6 和 Python 3.8 中看到不同的错误消息,如下所示,这是我遇到的问题
Python 3.6
(a,b) = None Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable
Python 3.8
(a,b) = None Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot unpack non-iterable NoneType object
解决方案 10:
因为使用 for 循环,而结果只是一个值,而不是一组值
波拉
@app.route("/search")
def search():
title='search'
search_name = request.form.get('search')
search_item = User.query.filter_by(id=search_name).first()
return render_template('search.html', title=title, search_item=search_item )
search.html(错误)
{% for p in search %}
{{ p }}
search.html(正确)
<td>{{ search_item }}</td>
解决方案 11:
这里的许多答案都暗示了这一点,但解决此错误(以及相关的TypeError: cannot unpack non-iterable NoneType object
)的方法不是尝试在发生此错误的行上修复它,而是修复生成的过程data
。例如,如果data
是从函数返回的值,则确保该函数返回一个可迭代对象(例如列表、numpy ndarray、pandas DataFrame 等)。如果data
是从某个 API 调用返回的值,请确保检查请求是否返回了可迭代对象。
例如在以下情况下,函数func()
打印一个值,该值隐式返回 None,一旦我们尝试对其进行迭代,就会导致标题中的 TypeError。
def func():
print('a string')
list(func()) # TypeError: 'NoneType' object is not iterable
相反,确保返回一个值:
def func():
return 'a string'
list(func()) # ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
解决方案 12:
我在 databricks 中使用 pandas 时遇到了这个错误。
此错误的解决方案是在集群中安装库,
在此处输入图像描述