[英]Understanding StopIteration handling inside generators for non-trivial case
[英]Python PEP479 Change StopIteration handling inside generators
有人可以帮助我了解PEP479的含义吗? 我正在阅读该文档,无法理解。
摘要说:
该PEP建议对生成器进行更改:在生成器内部引发StopIteration时,将其替换为RuntimeError。 (更确切地说,当异常即将从生成器的堆栈框架冒出时,会发生这种情况。)
例如,这样的循环是否仍然有效?
it = iter([1,2,3])
try:
i = next(it)
while True:
i = next(it)
except StopIteration:
pass
或这是否意味着如果我有这样的生成器定义:
def gen():
yield from range(5)
raise StopIteration
StopIteration
是否将由RuntimeError
替换?
如果有人能对此有所启发,我将不胜感激。
您的第一个循环应该仍然有效-当发电机用尽时, StopIteration
仍然会提高。
所不同的是, 有歧义时StopIteration
在发电机长大。 是因为生成器用完了要产生的东西而暗中提出了它?还是因为委托生成器用完了要产生的东西了(也许是由于next
调用)而引起了异常,并且没有正确处理异常,所以引起了它的出现? PEP-0479试图解决这种歧义。 现在,如果获得StopIteration
,则意味着您正在使用的生成StopIteration
完了要产生的项目。 换句话说,这意味着委托生成器在项目用尽时不会被错误处理。
为了支持此更改,您的生成器应return
而不是显式提高StopIteration
。
def gen():
yield from range(5)
return
如果您在启用StopIteration
和generator_stop
的情况下进行尝试,就会发生以下情况(当python3.7出现时,它将成为默认值):
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.