Python:不带await的异步函数

问题描述 投票:0回答:1

这是真的吗?

不包含

async
语句的
await
python 函数本身不会执行任何其他
async
函数,即使是由
await
调用调用。

FastAPI 示例

from fastapi import FastAPI


import some_arbirtrary_library

app = FastAPI()


async def no_await():
    # this can be any code provided it does not 
    # include an await statement
    result = some_arbitrary_library.some_arbitrary_function()
    return result


@app.get("/")
async def root():
    # Belief: this will not ever yield execution to any other
    # async operation (e.g. other async endpoints) because \
    # the guts of the function 'no_await' do not await on anything
    result = await no_await()
    return {"message": result}
#... other app endpoints defined with async def

这是一个有效的推论吗?

定义不包含

async
语句的函数
await
不会比以同步方式使用该函数提供任何性能增强。

python async-await fastapi
1个回答
0
投票

不包含await语句的异步Python函数 本身不会让执行任何其他异步函数,即使 由await 调用调用。

是的。在完成之前,它不会将控制权交还给事件循环。

定义不包含await语句的async函数 与使用该函数相比,没有提供任何性能增强 以同步方式。

是的,这也是真的。

async def
表示您将使用 IO 异步调用,因此您将使用
await
来实现这一点。你没有
await
吗?你不需要
async def

© www.soinside.com 2019 - 2024. All rights reserved.