PEP-380介绍 yield from
语法并说:
yield from <expr>
where 是一个评估为可迭代的表达式,从中提取迭代器。因此,以下内容是合法且有意义的:
@asyncio.coroutine
装饰器)因为生成器和基于生成器的协程都是 Iterable 的实例。然而,我不明白为什么
yield from native_coroutines (using async/await syntax)
合法吗?自 PEP-492声明 native 协程不实现
__iter__
和 __next__
方法,因此不可迭代。但是,没有 PEP 谈论这种 yield from 的行为变化,以接受 native 协程返回的协程对象?我知道基于生成器的协程将在 3.10 中被弃用,但我仍然想知道为什么
yield from
与 native 协程一起使用。
最佳答案
However, I fail to understand why
yield from native_coroutines
(using async/await syntax) is legal? Since PEP-492 states that native coroutines don't implement the__iter__
and__next__
methods and therefore aren't iterable.
但是,PEP 492 also states “基于生成器的协程 [...] 可以
yield from
本地协程对象。”However, I fail to understand why
yield from native_coroutines
is legal?
因为否则原生协程将无法从使用基于生成器的协程和
yield from
的遗留代码中使用。 .例如,在
async def
之后的某个时间点引入了大多数 asyncio 原语,包括 asyncio.sleep
, 被转换为 async def
协程。如果那些不支持 yield from
,转换将破坏所有等待的现有异步代码 asyncio.sleep
使用 yield from
,以前唯一可能的等待方式。这种向后不兼容会阻碍引入原生协程,所以它被避免了。
关于python-3.x - 为什么本地协程的 yield 语法是有效的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999942/