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

本文探讨了在Python生成器中使用return语句和raise StopIteration的区别。实际上,两者都会导致StopIteration异常被引发,但在Python中,直接使用return更符合语言规范。在Python 3.3之后,return语句会自动引发StopIteration并可以传递一个返回值作为异常的value属性。
摘要由CSDN通过智能技术生成

I'm curious about the difference between using raise StopIteration and a return statement in generators.

For example, is there any difference between these two functions?

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

I'm guessing the more "pythonic" way to do it is the second way (please correct me if I'm wrong), but as far as I can see both ways raise a StopIteration exception.

解决方案

There's no need to explicitly raise StopIteration as that's what a bare return statement does for a generator function - so yes they're the same. But no, just using return is more Pythonic.

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.

Or as @Bakuriu points out - the semantics of generators have changed slightly for Python 3.3, so the following is more appropriate:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值