yield from 关键字的 return 语句

我经常需要写一些比较复杂的代码,常常会遇到各种各样的问题。比如我在使用yield from 表达式时,return 语句的问题。我们知道,在使用 yield from 表达式时,return 语句的作用是在子生成器(被调用的生成器)执行完毕后,返回最终的结果到调用者。这可以让生成器在嵌套结构中更清晰地传递值。具体情况我会一一用文字记录下来,方便后期参考:

1、问题背景

使用 "yield from" 表达式时,return 语句的作用是什么?我在很多示例中都没有找到 return 语句从 yield from 表达式返回的值。我尝试了以下简单的代码,但没有成功:

csharp 复制代码
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 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 中有这样一段说明:

此外,当迭代器是另一个生成器时,子生成器被允许执行带有值的 return 语句,该值变为 yield from 表达式的值。

很显然,我没有得到这种解释。在 "yield from" 语句中,子生成器中的 return 语句是如何工作的?

2、解决方案

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

ruby 复制代码
def my_gen():
    yield 0
    return "done"
​
g = my_gen()
next(g)
next(g) # raises StopIteration: "done"

在 yield from 语句中返回的值将是此值。例如:

csharp 复制代码
def yield_from():
    res = yield from my_gen()
    assert res == "done"

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

答案2:

yield from generator 的简写为:

less 复制代码
for i in generator:
    yield i

好吧,它比这复杂一点:www.python.org/dev/peps/pe... 。如果 generator = 4,则它将无法正常工作。(你的 return4() 不是一个生成器,而是一个函数。)为了得到你想要的结果,你可以这样做:

python 复制代码
def yield_from():
    yield from range(4)
    yield 4

答案3:

我为你提供了测试的一个工作示例。return4 函数现在是一个生成器。为实现这一目标,必须在函数中任何地方出现 yield(Python 3.5 中有一个新的相关特性,但现在并不重要)。

正如你已经引用的:

此外,当迭代器是另一个生成器时,子生成器被允许执行带有值的 return 语句,该值变为 yield from 表达式的值。

总结:你将得到一个值。例如,你可以打印它:

python 复制代码
def yield_from():
    # ...
    val = yield from return4()
    print("value:", val)  # prints value: 4

但你希望的是 yield 它,而不是打印它。以下是完整的代码:

python 复制代码
def return4():
    if False:
        yield None
    return 4
​
def yield_from():
    yield from range(4)
    yield (yield from return4())
​
def test_yield_from():
    for x in yield_from():
        print(x)
​
test_yield_from()
# prints numbers 0 to 4

你可能会问自己,它有什么好处。当你只从生成器接收值时,几乎没有任何优势。但当你向生成器发送值时,yield from 是一个很棒的特性。尝试找到有关 Python 协程的良好解释。它很棒。

其实上面的问题我们知道,具体来说,当一个生成器函数中使用 yield from 调用另一个生成器时,return 语句的返回值会成为调用者获取的值。这就允许子生成器产生的值直接传递给调用者,而不需要在父生成器中一个一个地使用 yield 语句传递。所以后期有啥不懂的都可以评论区留言。

相关推荐
wuyk5552 天前
Spider-第11讲-工程化改造与可维护性
大数据·爬虫·elasticsearch·搜索引擎
wuyk5552 天前
Spider-第12讲-asyncio异步并发爬取
大数据·爬虫·elasticsearch·搜索引擎
小宋10212 天前
AI 爬虫把大学图书馆站点拖垮:按行为指纹给爬虫分类、按类发配额、用边缘缓存分层,以带宽成本结构和真实用户 P95 延迟定档
人工智能·爬虫·分类
wuyk5553 天前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
wuyk5553 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk5554 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
feasibility.4 天前
一物降一物?AI逆向没有终局:REA拆App,BLA设套,LASIK清场
人工智能·爬虫·github·逆向·skill·rea
wuyk5556 天前
Spider-第03讲-HTTP速通与读懂响应
网络·爬虫·网络协议·http
xyzzklk12 天前
在Open-WebUI中提升向量化速度
网络·人工智能·爬虫·ai·语言模型·自然语言处理·安卓
严肃小白兔12 天前
Cloudflare 开始区分 AI 爬虫与个人 Agent:网站访问控制应该怎样设计?
人工智能·爬虫