我有一个带有 return value
语句的生成器 . 如果我使用下一个,我会按预期得到Stopite: value
. 但是,当我使用 yield from
时, value
丢失了 .
In [1]: def test():
...: return 1
...: yield 2
...:
In [2]: t = test()
In [3]: t
Out[3]: <generator object test at 0x000000000468F780>
In [4]: next(t)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-4-9494367a8bed> in <module>()
----> 1 next(t)
StopIteration: 1
In [5]: def new():
...: yield from test()
...:
In [6]: n = new()
In [7]: n
Out[7]: <generator object new at 0x00000000050F23B8>
In [8]: next(n)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-8-1c47c7af397e> in <module>()
----> 1 next(n)
StopIteration:
有没有办法在使用 yield from
时保留 value
?这是按预期工作还是可能是一个错误?
1 回答
通过接收
yield from
语句中子生成器发送的值 .引自 PEP 380 -- Syntax for Delegating to a Subgenerator:
因此,通过小调整,
new
生成器中的res
将包含从test
子生成器引发的StopIteration
的值:现在执行
next(n)
时,您将获得Exception消息中的值:哦,作为附录,您当然可以通过再次使用
yield
获取'return'值而不将其封装在StopIteration
对象中:现在调用
next(new())
将返回从test()
返回的值: