簡體   English   中英

從具有返回<value>語句的生成器中獲取

[英]yield from a generator that has return <value> statement in it

我有一個帶有return value語句的生成器。 如果我使用下一個,我會按預期獲得Stopiteration: value 但是當我使用yield fromvalue就丟失了。

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語句中發送的值。

PEP 380中獲取報價- 委托給子發電機的語法:

表達式的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM