gpt4 book ai didi

python - 使用 "yield from"表达式时 return 有什么作用?

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:00 24 4
gpt4 key购买 nike

我无法从yield from expression 中找到返回值的任何示例.我试过这个简单的代码,但没有成功:

def return4():
return 4


def yield_from():
res = yield from range(4)
res = yield from return4()


def test_yield_from():
for x in yield_from():
print(x)


test_yield_from()

产生:

» python test.py 
0
1
2
3
Traceback (most recent call last):
File "test.py", line 52, in <module>
test_yield_from()
File "test.py", line 48, in test_yield_from
for x in yield_from():
File "test.py", line 44, in yield_from
res = yield from return4()
TypeError: 'int' object is not iterable

但我期待:

» python test.py 
0
1
2
3
4

因为,如 PEP 中所述:

Furthermore, when the iterator is another generator, the subgenerator is allowed to execute a return statement with a value, and that value becomes the value of the yield from expression.

显然,我没有得到这个解释。 “子生成器”中的 return 如何处理 yield from

最佳答案

生成器可以在耗尽时返回一个值:

def my_gen():
yield 0
return "done"

g = my_gen()
next(g)
next(g) # raises StopIteration: "done"

yield from 语句中的返回值将是这个值。例如。

def yield_from():
res = yield from my_gen()
assert res == "done"

默认情况下,此值为 None。即 res = yield from range(4) 会将 res 设置为 None

关于python - 使用 "yield from"表达式时 return 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com