Python PEP479更改生成器内的StopIteration处理

Jac*_*din 8 python runtime-error stopiteration

有人可以帮我理解PEP479是关于什么的吗?我正在阅读文档而无法理解它.

摘要说:

此PEP建议对生成器进行更改:当在生成器内引发StopIteration时,将其替换为RuntimeError.(更准确地说,当异常即将从生成器的堆栈帧中冒出时,就会发生这种情况.)

那么,例如,这样的循环是否仍然有效?

it = iter([1,2,3])
try:
    i = next(it)
    while True:
        i = next(it)
except StopIteration:
    pass
Run Code Online (Sandbox Code Playgroud)

或者它是否意味着如果我有这样的生成器定义:

def gen():
    yield from range(5)
    raise StopIteration
Run Code Online (Sandbox Code Playgroud)

StopIteration将要被替换RuntimeError

如果有人能够对此有所了解,我将非常感激.

mgi*_*son 11

你的第一个循环应该仍然有效 - StopIteration当发电机耗尽时仍然会升起.

所不同的是,有歧义时,StopIteration以发电机长大.它是否被提升(隐式)是因为生成器耗尽了产生的东西 - 或者是因为委托生成器耗尽了产生的东西(可能是由于next调用)并且异常处理得不好而引发了它?PEP-0479试图解决这种模糊性.现在,如果你得到了一个StopIteration,那就意味着你正在使用的生成器耗尽了产品.换句话说,这意味着代理生成器在用完项目时没有被错误处理.

要支持此更改,您的生成器应该return而不是StopIteration显式提升.

def gen():
    yield from range(5)
    return
Run Code Online (Sandbox Code Playgroud)

如果你使用StopIterationgenerator_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
Run Code Online (Sandbox Code Playgroud)