gpt4 book ai didi

python - 自定义 python 生成器中的 Return 和 StopIteration

转载 作者:行者123 更新时间:2023-12-02 00:18:41 25 4
gpt4 key购买 nike

阅读 Python 中的一些新风格观点,并着手了解生成器中从 StopIterationreturn 的转变。我的主要问题是这在自定义生成器中应该如何工作。我有一个类,我直接覆盖了 __next__ 方法,因为我必须添加一些逻辑来跟踪生成。

下面非常接近我正在做的事情,包含所有关键元素。请注意,我实际上并不是在创建一个复制列表的生成器,只是将其作为一个最小示例。

class Test():
items = <list>

def __init__(self):
self.index = 0

def __next__(self):
if self.index >= len(self.items):
raise StopIteration
value = self.items[self.index]
self.index += 1
return value

def reset(self):
self.index = 0

所以在这种情况下,我会遍历一个列表直到它耗尽,然后下游调用将决定是重置生成器还是在它耗尽后继续前进。但是,如何在不使用 StopIteration 的情况下启用类似的功能,因为它已被弃用?在此处使用 return 引发 StopIteration 的标准建议似乎并不适用,我真的不想更改下游代码来检查产生 的生成器无

那么我应该在这里做什么呢? StopIteration 异常在 __next__ 中是否仍然可以接受?

最佳答案

StopIteration 没有被弃用,您只是误解了生成器是什么。你实际上没有生成器,你有一个迭代器。生成器只是使用 yield 创建迭代器的函数。

您在不使用生成器的情况下创建自己的基本迭代器实现。迭代器在完成时从 __next__ 引发 StopIterator。您的代码在此处正确执行此操作。

来自Generator Types section Python 数据模型文档:

Python’s generators provide a convenient way to implement the iterator protocol. If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods. More information about generators can be found in the documentation for the yield expression.

来自同一文档,在 Iterator Types section 中:

iterator.__next__()
Return the next item from the container. If there are no further items, raise the StopIteration exception.

有一个弃用,但这只涉及在生成器函数中使用 StopIteration。参见 PEP 479 - Change StopIteration handling inside generators :

This PEP proposes a change to generators: when StopIteration is raised inside a generator, it is replaced it with RuntimeError. (More precisely, this happens when the exception is about to bubble out of the generator's stack frame.) Because the change is backwards incompatible, the feature is initially introduced using a __future__ statement.

在生成器内部,使用return 会触发StopIteration 异常。手动引发 StopIteration 实际上会产生隐蔽的错误,因为结果迭代器的任何使用者都无法区分异常的正确使用和不正确、意外 StopIteration 从您的生成器发出的异常。这使得此类问题难以调试,这就是为什么它们在生成器函数中的使用在未来的 Python 版本中会发生变化。

旁注:您的实现需要 iterator.__iter__() method ,它只返回 self

关于python - 自定义 python 生成器中的 Return 和 StopIteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56189466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com