返回生成器以及Python 3.3中的yield [英] Return in generator together with yield in Python 3.3

查看:74
本文介绍了返回生成器以及Python 3.3中的yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2中,函数定义中return和yield一起出现错误.但是对于Python 3.3中的这段代码

In Python 2 there was an error when return was together with yield in function definition. But for this code in Python 3.3

def f():
  return 3
  yield 2

x = f()
print(x.__next__())

在带有yield的函数中没有使用return的错误.但是,当调用函数__next__时,会引发StopIteration异常.为什么不只返回值3?此返回是否以某种方式被忽略了?

there is no error that return is used in function with yield. However when the function __next__ is called then there is thrown exception StopIteration. Why there is not just returned value 3? Is this return somehow ignored?

推荐答案

这是Python 3.3中的一项新功能(如注释所述,它甚至在3.2中也不起作用).就像生成器中的return长期以来一直等同于raise StopIteration()一样,生成器中的return <something>现在等同于raise StopIteration(<something>).因此,您看到的异常应打印为StopIteration: 3,并且可以通过异常对象上的属性value访问该值.如果使用(也是新的)yield from语法委派生成器,则为结果.有关详细信息,请参见 PEP 380 .

This is a new feature in Python 3.3 (as a comment notes, it doesn't even work in 3.2). Much like return in a generator has long been equivalent to raise StopIteration(), return <something> in a generator is now equivalent to raise StopIteration(<something>). For that reason, the exception you're seeing should be printed as StopIteration: 3, and the value is accessible through the attribute value on the exception object. If the generator is delegated to using the (also new) yield from syntax, it is the result. See PEP 380 for details.

def f():
    return 1
    yield 2

def g():
    x = yield from f()
    print(x)

# g is still a generator so we need to iterate to run it:
for _ in g():
    pass

这会打印1,但不会打印2.

This prints 1, but not 2.

这篇关于返回生成器以及Python 3.3中的yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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