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

标签 python-3.x python-asyncio python-3.3

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/

    相关文章:

    python-3.x - 在 Python Azure 函数中,如何仅用一行代码将共享库导入到我的函数中?

    python - 我是否需要创建 session 表才能使用 Flask-Session SqlAlchemySessionInterface

    python - 我应该在 asyncio 中使用协议(protocol)还是流?

    python - 从 asyncio.Protocol.data_received 调用协程

    Python、Ubuntu : Install PyPi package for a specific Python version

    python-3.x - 查找 python 数组变为正数(但不是负数)的索引

    python-3.x - Pandas 获取 Cell 中每个元组的第一个元素

    python - 不确定为什么异步任务在事件循环之外完成

    python - 打印列表中的项目数

    python - 如何读取多个文件并进行错误检查?