在Python中,异步生成器函数是协程,生成器函数也是协程。
生成器函数和异步生成器函数的用途有什么区别?
谢谢。
最佳答案
目的PEP 525 -- Asynchronous Generators与 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简单的。正如生成器对迭代器协议(protocol)所做的那样。
不必定义实现 __aiter__
和 __anext__
的对象,您可以创建一个异步生成器,它似乎是通过魔术来完成的。这反射(reflect)了生成器为迭代器协议(protocol)所做的事情;您可以创建一个生成器,而不是为对象实现 __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.
只是在这里添加一些术语,因为有时很难跟踪术语:
- 生成器:包含一个或多个
yield
表达式的def
函数。 - 基于生成器的协程:由
types.coroutine
包装的生成器 (def
+yield
) .如果您需要将其视为协程对象,则需要将其包装在types.coroutine
中。 - 异步生成器:包含一个或多个
yield
表达式的async def
函数。这些也可以包含await
表达式。 - 协程:
async def
没有零个或多个await
并且没有yield
。
关于python - 生成器函数和异步生成器函数的用途有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46203876/