繁体   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