在 Python 3.3 中与生成器一起返回生成器 [英] Return in generator together with yield in Python 3.3

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

问题描述

在 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__())

在函数中使用 return 和 yield 没有错误.然而,当函数 __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 在生成器中现在等价于 <代码>引发 StopIteration().因此,您看到的异常应该打印为 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 中与生成器一起返回生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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