简体   繁体   English

当没有更多元素可以产生时,Python生成器是否应该引发异常?

[英]Should a Python generator raise an exception when there are no more elements to yield?

Should a Python generator raise an exception when there are no more elements to yield? 当没有更多元素可以产生时,Python生成器是否应该引发异常?

Which one? 哪一个?

The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. 我知道你必须手动raise StopIteration的唯一一次是在类上实现next()方法以表示迭代器已终止。 For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for you. 对于生成器(其中包含yield语句的函数),函数的结尾或return语句将为您正确触发StopIteration

It doesn't have to, but it can raise a StopIteration . 它没有,但它可以引发StopIteration

The more normal way to end the iteration is to let the function end and return naturally, or to use a return statement. 结束迭代的更常用的方法是让函数结束并自然返回,或者使用return语句。 This will cause a StopIteration to be raised on your behalf. 这将导致代表您提出StopIteration。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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