python - raise StopIteration 和生成器中的 return 语句有什么区别?

标签 python generator stopiteration

我很好奇在生成器中使用 raise StopIterationreturn 语句之间的区别。

例如,这两个功能有什么区别吗?

def my_generator0(n):
    for i in range(n):
        yield i
        if i >= 5:
            return

def my_generator1(n):
    for i in range(n):
        yield i
        if i >= 5:
            raise StopIteration

我猜测更“pythonic”的方式是第二种方式(如果我错了,请纠正我),但据我所知,两种方式都会引发 StopIteration异常(exception)。

最佳答案

没有必要显式地引发 StopIteration ,因为这是一个简单的 return 语句对生成器函数所做的 - 所以是的,它们是相同的。但是不,只使用 return 更符合 Python 风格。

发件人:http://docs.python.org/2/reference/simple_stmts.html#the-return-statement (适用于 Python 3.2)

In a generator function, the return statement is not allowed to include an expression_list. In that context, a bare return indicates that the generator is done and will cause StopIteration to be raised.

或者正如@Bakuriu 指出的那样——Python 3.3 中生成器的语义略有变化,因此以下更合适:

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

关于python - raise StopIteration 和生成器中的 return 语句有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14183803/

相关文章:

python - 即使在路径上也无法导入 importlib

PHP 生成器产生第一个值,然后遍历其余值

Python seaborn histplot 返回 StopIteration

python - 如何用另一个数据框元素替换数据框元素

python - 从列表创建一个完整的二叉搜索树

python - Pandas Dataframe 合并而不复制任何一方?

Python 生成器和产量 : How to know which line the program is at

python - 在 python 中将 str.join 与生成器表达式一起使用

使用 list(map(...)) 时无法引发 Python3 StopIteration 错误

python - 遍历列表并在 Python 中漂亮地处理 StopIteration