Python PEP479 Change StopIteration handling inside generators

流过昼夜 提交于 2019-12-01 04:05:39

Your first loop should still work -- StopIteration will still be raised when a generator is exhausted.

The difference is that there was ambiguity when a StopIteration was raised in a generator. Did it get raised (implicitly) because the generator ran out of things to yield -- Or did it get raised because a delegate generator ran out of things to yield (maybe due to a next call) and the exception wasn't handled properly? PEP-0479 tries to address that ambiguity. Now if you get a StopIteration, it means that the generator you are working with ran out items to yield. Said another way, it means that a delegate generator didn't get mis-handled when running out of items.

To support this change, your generator should return instead of raising StopIteration explicitly.

def gen():
    yield from range(5)
    return

Here's what happens if you try it with the StopIteration and generator_stop enabled (which will become the default when python3.7 comes around):

>>> from __future__ import generator_stop
>>> def gen():
...     yield from range(5)
...     raise StopIteration
... 
>>> list(gen())
Traceback (most recent call last):
  File "<stdin>", line 3, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!