返回生成器以及Python 3.3中的yield


问题内容

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

def f():
  return 3
  yield 2

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

没有错误,return与函数一起使用yield。但是,__next__调用该函数时会引发StopIteration异常。为什么不只是返回值3?这个回报以某种方式被忽略了吗?


问题答案:

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

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