[英]yield from a generator that has return <value> statement in it
我有一個帶有return value
語句的生成器。 如果我使用下一個,我會按預期獲得Stopiteration: 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
? 這是按預期工作還是可能是一個錯誤?
通過接收子語言生成器在yield from
語句中發送的值。
表達式的
yield from
的值是迭代器終止時引發的StopIteration
異常的第一個參數。
因此,通過小調整, new
成器中的res
將包含從test
子生成器引發的StopIteration
的值:
def new():
res = yield from test()
return res
現在,當執行next(n)
,您將獲得Exception消息中的值:
n = new()
next(n)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-39-1c47c7af397e> in <module>()
----> 1 next(n)
StopIteration: 1
哦,作為附錄,當然可以通過再次使用yield
獲取'return'值而不將其封裝在StopIteration
對象中:
def new():
res = yield from test()
yield res
現在調用next(new())
將返回test()
返回的值:
next(new())
Out[20]: 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.