简体   繁体   中英

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()

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. 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. They implicitly return None . foo will nonetheless generate an iterator as it includes a yield statement.

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 .

The yield 1, 2 makes the difference. foo returns:

<generator object foo at 0x7f9e01a91d70>

bar returns:

None

If you'd comment the yield part the code would crash on foo() too.

You should return two values for each of the methods to solve it.

If your function does not include statement and you want it to return "empty iterator" you should write 语句,并且希望它返回“空迭代器”,则应编写

def empty()
    raise StopIteration

for each in empty():
    print('this will never show up')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM