生成器函数和异步生成器函数的用途有什么区别

What are the differences between the purposes of generator functions and asynchronous generator functions

在Python中,异步生成器函数是协程,生成器函数也是协程。

生成器函数和异步生成器函数的用途有何不同?

谢谢。

PEP 525 -- Asynchronous Generators is pretty much similar to PEP 255 -- Simple Generators 引入生成器的目的。它的主要目的是让事情 更容易 实施,只是在不同的领域(异步领域)。来自 PEP 525:

Essentially, the goals and rationale for PEP 255, applied to the asynchronous execution case, hold true for this proposal as well.

简而言之,它使编写支持 asynchronous iteration protocol 的对象变得容易。正如 generatorsiterator protocol 所做的那样。

您不必定义实现 __aiter____anext__ 的对象,而是创建一个异步生成器,它似乎是通过魔术来完成的。这反映了生成器为迭代器协议所做的事情;您可以创建一个生成器,而不是为对象实现 __iter____next__

这在 PEP 525 的合理性中得到了很好的说明,其中还包括一个很好的示例,该示例显示了使用异步生成器时编写的代码所节省的成本。

除了节省代码长度外,异步生成器的性能也更好:

Performance is an additional point for this proposal: in our testing of the reference implementation, asynchronous generators are 2x faster than an equivalent implemented as an asynchronous iterator.


只是在这里添加一些术语,因为有时很难跟踪术语:

  • 生成器:def 包含一个或多个 yield 表达式的函数。
  • 基于生成器的协程:由 types.coroutine 包装的生成器 (def + yield)。如果您需要将其视为协程对象,则需要将其包装在 types.coroutine 中。
  • 异步生成器:async def 包含一个或多个 yield 表达式的函数。这些也可以包含 await 表达式。
  • 协程:async def 没有零个或多个 await,也没有 yield