python - 为什么我要使用 `async def` 而不是 `@asyncio.coroutine`?

标签 python python-3.x asynchronous async-await backwards-compatibility

Python 3.5 使用新的函数定义语法极大地扩展了对异步编程的支持。而异步函数以前只是“有好处的生成器”:

def generate_numbers():
    """
    Generator function that lazily returns 1 - 100
    """
    for i in range 100:
        yield i

generate_async = asyncio.coroutine(generate_numbers)
generate_async.__doc__ = """
    Coroutine that lazily returns 1 - 100
    This can be used interchangeably as a generator or a coroutine
    """

它们现在有自己的特殊声明语法和特殊行为,它们不再像通常的生成器函数那样使用:

aysnc def generate_async_native():
    """
    A coroutine that returns 1 - 100
    This CANNOT be used as a generator, and can ONLY be executed by running it from an event loop
    """
    for i in range(100):
        await i

不是关于这些类型之间的功能或实际差异的问题 -- 在 this StackOverflow answer 中讨论。 .

我的问题是:为什么我要使用 async def?与 @asyncio.coroutine 相比,它似乎没有提供额外的好处,但会增加额外的成本

  1. 打破了向后兼容性(带有 async def 的 Python 3.5 代码 在旧版本中甚至不会解析,尽管这可以说是一个功能而不是错误)和
  2. 似乎在如何调用函数方面提供了较少的灵 active 。

最佳答案

Martijn Pieters 给出了一个可能的答案:

The advantages are that with native support, you can also introduce additional syntax to support asynchronous context managers and iterators. Entering and exiting a context manager, or looping over an iterator then can become more points in your co-routine that signal that other code can run instead because something is waiting again

这实际上已经通过新的 async withasync for 语法实现了,这不能像装饰的“附加”解决方案那样容易地实现发电机。

关于python - 为什么我要使用 `async def` 而不是 `@asyncio.coroutine`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40577684/

相关文章:

python - 制作一个处理所有错误的函数正常吗?

python - 如何合并列表列表中具有共同元素的列表?

java - Java EE 中的异步执行

python - try 和 except 都引发异常。

python - Django CBV属性错误: Generic detail view must be called with either an object pk or a slug

python - Pyspark - 根据其他值的比较删除具有匹配值的行

javascript - Python 中的 jQuery $.param'ed 字符串解析(应用引擎)

python-3.x - 当我使用 linux penguin 在 chromebook 上安装 python 3.9 时,我仍然看到旧版本

来自模板的 Node.js 异步调用

c# - SQLite 在 CreateTablesAsync 上挂起 - Xamarin Forms