首页 > 解决方案 > python3 asyncio:堆栈中的所有函数都必须使用等待/异步吗

问题描述

使用时await/async,是否必须“一直向上”,意思是调用链中的每个函数都必须使用它吗?

例如:

def a():
    # can't call b() here

async def b():
    return await c

async def c():
    return ...

我最近在 gevent 下运行的烧瓶应用程序的上下文中想知道这一点,其中一个端点是一个长时间运行的调用,应该“检查”,而不是阻塞其他调用

def handler0():
    # short running
    return ...

def handler():  # blocks handler0
    return await some_long_thing()

async def some_long_thinig():
    # ..do somethiing
    return ...

标签: python-3.xpython-asyncio

解决方案


调用链中的每个函数都必须使用它吗?

当您使用asyncio模块时,每个功能都await应该被定义为async(应该是协程本身)。

大多数顶级协程通常是脚本的主要入口点,并由事件循环使用asyncio.run()或类似函数执行。

这就是asyncio 设计方式:通过这种方式,您始终知道上下文是否可以在特定位置切换。


推荐阅读