问题:TypeError:“ NoneType”对象在Python中不可迭代

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

我在以下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)

What does error TypeError: 'NoneType' object is not iterable mean?

I am getting it on this Python code:

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)

回答 0

这表示datais 的值None

It means the value of data is None.


回答 1

错误说明:“ 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

类型是偷偷摸摸的,可以从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的变量进行迭代。通过__iter__在None上调用该方法来执行该操作。

None没有__iter__定义方法,因此Python的虚拟机会告诉您所看到的内容:NoneType没有__iter__方法。

这就是为什么Python的鸭式思维被认为是不好的。程序员使用变量进行了完全合理的操作,在运行时它被None污染,python虚拟机试图继续运行,并在地毯上吐出一堆无关紧要的废话。

Java或C ++没有这些问题,因为不允许您编译此类程序,因为您没有定义发生None时的处理方法。Python允许您执行很多在特殊情况下无法预期的工作,从而为程序员提供了很多上锁的绳索。Python是一个肯定的人,当它像Java和C ++那样阻止您伤害自己时,说是肯定的先生。

Explanation of error: ‘NoneType’ object is not iterable

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

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

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

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

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

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

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 is to check for None because is is 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

NoneTypes are Sneaky, and can sneak in from 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:

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

Concatenation of None and a string:

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.

None has no __iter__ method defined, so Python’s virtual machine tells you what it sees: that NoneType has no __iter__ method.

This is why Python’s duck-typing ideology 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.

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.


回答 2

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

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

有什么问题data吗?其类型为NoneType。只有None类型NoneType。这样data is None

您可以在IDE中进行验证,也可以通过print "data is", repr(data)for语句之前插入例如并重新运行来进行验证。

考虑下一步需要做什么: 应如何表示“无数据”?我们写一个空文件吗?我们是否引发异常或记录警告或保持沉默?

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

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

What’s the problem with data? Its type is NoneType. Only None has type NoneType. So data is None.

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

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?


回答 3

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

例:

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进行遍历”

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.

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”


回答 4

这意味着数据变量正在传递None(类型为NoneType),等效于没有。因此,正如您正在尝试的那样,它不能作为列表进行迭代。

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.


回答 5

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

write_file(foo, bar)

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

You’re calling write_file with arguments like this:

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.


回答 6

对我来说,这是戴Groovy帽子而不是Python 3的情况。

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

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

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

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

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

Forgot the return keyword at the end of a def function.

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 (or Rust) way.

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

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。