Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 asyncio: do all functions in a stack have to use await/async

When using await/async, does it have to go "all the way up", meaning, does every function in the call chain have to use it?

E.g.:

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

async def b():
    return await c

async def c():
    return ...

I recently wondered this in the context of a flask app running under gevent, where one of the endpoints was a long running call that should be "checked upon", while not blocking other calls

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

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

async def some_long_thinig():
    # ..do somethiing
    return ...
like image 246
Tommy Avatar asked Nov 06 '22 17:11

Tommy


1 Answers

does every function in the call chain have to use it?

When you use asyncio module every function that await for something should be defined as async (should be a coroutine itself).

Most top level coroutine usually is main entry point of your script and executed by event loop using asyncio.run() or similar function.

This is how asyncio designed: this way you always know if context can be or can't be switched in particular place.

like image 97
Mikhail Gerasimov Avatar answered Nov 15 '22 13:11

Mikhail Gerasimov