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

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

当前回答

错误解释:“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,因为它对身份检查更健壮。不要使用相等操作,因为这些操作本身就会产生泡沫。Python的编码风格指南- PEP-008

NoneTypes是鬼鬼祟祟的,可以从lambdas潜入:

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++一样。

其他回答

对我来说,这就像是我戴上了Groovy的帽子,而不是Python 3的帽子。

在def函数末尾忘记return关键字。

已经有几个月没有认真地编写Python 3了。正在考虑在例程中计算的最后一个语句是按照Groovy(或Rust)的方式返回的。

进行了几次迭代,查看堆栈跟踪,插入try:…except TypeError:…块调试/步进代码以找出错误所在。

该消息的解决方案当然没有使错误跳出来。

当你得到None Exception时,继续循环,

例子:

   a = None
   if a is None:
       continue
   else:
       print("do something")

这可以是来自DB或excel文件的任何可迭代对象。

我在数据库里对熊猫犯了这个错误。

此错误的解决方案是在集群中安装库 在这里输入图像描述

另一种可能产生这种错误的情况是,当你设置某个值等于函数的返回值时,却忘记实际返回任何值。

例子:

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来迭代"

因为使用for循环的结果只是一个值,而不是一组值

pola.py

@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>