TypeError:'NoneType' 对象在 Python 中不可迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3887381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:11:56  来源:igfitidea点击:

TypeError: 'NoneType' object is not iterable in Python

pythonnonetype

提问by l--''''''---------''''''''''''

What does error TypeError: 'NoneType' object is not iterablemean?

错误TypeError: 'NoneType' object is not iterable是什么意思?

I am getting it on this Python code:

我在这个 Python 代码上得到了它:

def write_file(data, filename): # creates file and writes list to it
  with open(filename, 'wb') as outfile:
    writer = csv.writer(outfile)
    for row in data: # ABOVE ERROR IS THROWN HERE
      writer.writerow(row)

采纳答案by vanza

It means the value of datais None.

这意味着 的值dataNone

回答by clee

You're calling write_file with arguments like this:

您正在使用如下参数调用 write_file:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

但是您没有正确定义 'foo',或者您的代码中有错字,因此它创建了一个新的空变量并将其传入。

回答by Rod

It means that the data variable is passing None (which is type NoneType), its equivalent for nothing. So it can't be iterable as a list, as you are trying to do.

这意味着数据变量正在传递 None (它是 NoneType 类型),它等效于nothing。所以它不能作为一个列表迭代,就像你试图做的那样。

回答by John Machin

Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable

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

Which object is it complaining about? Choice of two, rowand data. In for row in data, which needs to be iterable? Only data.

它在抱怨哪个对象?二选一,rowdata。在 中for row in data,哪个需要可迭代?只有data

What's the problem with data? Its type is NoneType. Only Nonehas type NoneType. So data is None.

有什么问题data?它的类型是NoneType. 只有None类型NoneType。所以data is None

You can verify this in an IDE, or by inserting e.g. print "data is", repr(data)before the forstatement, and re-running.

您可以在 IDE 中验证这一点,或者print "data is", repr(data)for语句前插入 eg ,然后重新运行。

Think about what you need to do next:How should "no data" be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?

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

回答by Eric Leschinski

Explanation of error: 'NoneType' object is not iterable

错误说明:“NoneType”对象不可迭代

In python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:

在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.

Iterating over a variable that has value None fails:

迭代具有值 None 的变量失败:

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

Python methods return NoneType if they don't return a value:

如果 Python 方法不返回值,则返回 NoneType:

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

You need to check your looping constructs for NoneType like this:

您需要像这样检查 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 says only use isto check for Nonebecause isis more robust to identity checking. Don't use equality operations because those can spit bubble-up implementationitis of their own. Python's Coding Style Guidelines - PEP-008

Guido 说只用于is检查,None因为is它对身份检查更健壮。不要使用相等操作,因为它们会吐出自己的冒泡实现。 Python 的编码风格指南 - PEP-008

NoneTypes are Sneaky, and can sneak in from lambdas:

NoneTypes 是 Sneaky,并且可以从 lambdas 中偷偷进入:

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

NoneType is not a valid keyword:

NoneType 不是有效的关键字:

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

Concatenation of Noneand a string:

None和一个字符串的连接:

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

What's going on here?

这里发生了什么?

Python's interpreter converted your code to pyc bytecode. The Python virtual machine processed the bytecode, it encountered a looping construct which said iterate over a variable containing None. The operation was performed by invoking the __iter__method on the None.

Python 的解释器将您的代码转换为 pyc 字节码。Python 虚拟机处理了字节码,它遇到了一个循环结构,该结构表示迭代包含 None 的变量。该操作是通过调用__iter__None 上的方法来执行的。

None has no __iter__method defined, so Python's virtual machine tells you what it sees: that NoneType has no __iter__method.

None 没有__iter__定义方法,所以 Python 的虚拟机告诉你它看到了什么: NoneType 没有__iter__方法。

This is why Python's duck-typingideology is considered bad. The programmer does something completely reasonable with a variable and at runtime it gets contaminated by None, the python virtual machine attempts to soldier on, and pukes up a bunch of unrelated nonsense all over the carpet.

这就是为什么Python 的鸭子类型意识形态被认为是糟糕的。程序员用一个变量做了一些完全合理的事情,在运行时它被 None 污染,python 虚拟机试图继续前进,并在地毯上吐出一堆无关的废话。

Java or C++ doesn't have these problems because such a program wouldn't be allowed to compile since you haven't defined what to do when None occurs. Python gives the programmer lots of rope to hang himself by allowing you to do lots of things that should cannot be expected to work under exceptional circumstances. Python is a yes-man, saying yes-sir when it out to be stopping you from harming yourself, like Java and C++ does.

Java 或 C++ 没有这些问题,因为这样的程序不允许编译,因为您还没有定义在 None 发生时要做什么。Python 允许程序员做很多在特殊情况下不能工作的事情,从而为程序员提供了很多可以吊死自己的绳索。Python 是一个肯定的人,当它阻止你伤害自己时说 yes-sir,就像 Java 和 C++ 那样。

回答by gunslingor

Another thing that can produce this error is when you are setting something equal to the return from a function, but forgot to actually return anything.

可能产生此错误的另一件事是当您设置与函数返回值相等的内容时,但实际上忘记了返回任何内容。

Example:

例子:

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)

This is a little bit of a tough error to spot because the error can also be produced if the row variable happens to be None on one of the iterations. The way to spot it is that the trace fails on the last line and not inside the function.

这是一个很难发现的错误,因为如果行变量在一次迭代中恰好是 None ,也会产生错误。发现它的方法是跟踪在最后一行失败,而不是在函数内部。

If your only returning one variable from a function, I am not sure if the error would be produced... I suspect error "'NoneType' object is not iterable in Python" in this case is actually implying "Hey, I'm trying to iterate over the return values to assign them to these three variables in order but I'm only getting None to iterate over"

如果你只从函数返回一个变量,我不确定是否会产生错误......我怀疑错误“'NoneType'对象在Python中不可迭代”在这种情况下实际上暗示“嘿,我正在尝试迭代返回值以将它们按顺序分配给这三个变量,但我只得到 None 来迭代”

回答by JGFMK

For me it was a case of having my Groovy haton instead of the Python 3 one.

对我来说,这是一个戴上 Groovy 帽子而不是 Python 3的例子。

Forgot the returnkeyword at the end of a deffunction.

忘记returndef函数末尾的关键字。

Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy way.

已经有几个月没有认真地编写 Python 3 了。认为在例程中评估的最后一条语句是按照 Groovy 方式返回的。

Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ...block debugging/stepping thru code to figure out what was wrong.

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

The solution for the message certainly did not make the error jump out at me.

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