生成器中的raise StopIteration和return语句有什么区别? [英] What is the difference between raise StopIteration and a return statement in generators?

查看:2016
本文介绍了生成器中的raise StopIteration和return语句有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我猜想第二种方法是更"pythonic"的方法(如果我错了,请纠正我),但据我所知,这两种方法都会引发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.

推荐答案

不需要显式地提高StopIteration,因为这是裸露的return语句对生成器函数的作用-所以是的,它们是相同的.但是,不,只是使用return更像Pythonic.

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.

来自: http://docs.python.org/2/reference/simple_stmts .html#the-return-statement (对Python 3.2有效)

From: http://docs.python.org/2/reference/simple_stmts.html#the-return-statement (valid to Python 3.2)

在生成器函数中,不允许return语句包含expression_list.在这种情况下,简单的返回指示生成器已完成,并将导致StopIteration升高.

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略有变化,因此以下更合适:

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

在生成器函数中,return语句指示生成器已完成,并将引起StopIteration升高.返回的值(如果有)用作构造StopIteration的参数,并成为StopIteration.value属性.

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.

这篇关于生成器中的raise StopIteration和return语句有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆