gpt4 book ai didi

python-3.x - 为什么本地协程的 yield 语法是有效的

转载 作者:行者123 更新时间:2023-12-01 04:27:42 26 4
gpt4 key购买 nike

PEP-380介绍 yield from语法并说:

yield from <expr>

where 是一个评估为可迭代的表达式,从中提取迭代器。因此,以下内容是合法且有意义的:
  • 发电机产量
  • 从 generator_based_coroutine 产生(使用 @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/

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