[英]weird TypeError: 'NoneType' object is not iterable
I encounter a weird error. 我遇到一个奇怪的错误。 As these codes, both foo()
and bar()
return None
, but it raises TypeError only when iterating bar()
就像这些代码一样, foo()
和bar()
返回None
,但是仅在迭代bar()
时才会引发TypeError。
def foo():
if True:
return
yield 1, 2
def bar():
return
for a, b in foo():
print a + b
for a, b in bar():
print a + b
Because foo
includes a yield
statement, it is a generator, so the result from the return is always a generator object even if the actual yield statement can't be reached. 由于foo
包含yield
语句,因此它是生成器,因此即使无法达到实际的yield语句,返回的结果始终是生成器对象。 A generator is true in a boolean sense, hence your result. 从布尔意义上讲,生成器是正确的,因此可以得到结果。
If you 如果你
print foo()
print bar()
you get 你得到
<generator object foo at 0x7f8a79fd5eb0>
None
In your functions foo
and bar
, they both reach an empty return
statement. 在函数foo
和bar
,它们都到达一个空的return
语句。 They implicitly return None
. 他们隐式return None
。 foo
will nonetheless generate an iterator as it includes a yield
statement. 但是foo
将生成一个迭代器,因为它包含yield
语句。
Therefore as you are looping over the output of the functions, foo
will use the iterator values, while bar
will not, resulting in a TypeError
. 因此,当您遍历函数的输出时, foo
将使用迭代器值,而bar
将不使用迭代器值,从而导致TypeError
。
The yield 1, 2 makes the difference. 产量1、2有所不同。 foo returns: foo返回:
<generator object foo at 0x7f9e01a91d70>
bar returns: 条返回:
None
If you'd comment the yield part the code would crash on foo() too. 如果您要注释yield部分,那么代码也会在foo()上崩溃。
You should return two values for each of the methods to solve it. 您应该为每种方法返回两个值来解决它。
If your function does not include yield statement and you want it to return "empty iterator" you should write 如果您的函数不包含yield语句,并且希望它返回“空迭代器”,则应编写
def empty()
raise StopIteration
for each in empty():
print('this will never show up')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.