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

标签 python python-3.x asynchronous python-3.6 coroutine

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

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

谢谢。

最佳答案

目的PEP 525 -- Asynchronous GeneratorsPEP 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/

相关文章:

python / Selenium /火狐 : Can't start firefox with specified profile path

python - 正则表达式:python 其他结果作为 regexr

python - 嗨,将 python 中的值设置为列表中的任何索引的更 pythonic 方法是什么?

R-在可变间隔上计算滚动统计信息的更快方法

iphone - 异步回调已解除的 View Controller ?

Python:选择位数来表示二进制数

python - 如何导入预训练的 InceptionV4 模型来在 Kaggle 中训练我们的模型?

python - “elif”在 'while' 循环内不起作用

python - 如何解决我的音乐游戏中的这个问题?

asynchronous - 一旦异步: run f# async function exactly once