我很好奇在生成器中使用 raise StopIteration
和 return
语句之间的区别。
例如,这两个功能有什么区别吗?
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/