What is the point of having to put await in front of each async function in Python?

Viewed 2337
2 Answers

Using await does NOT make the call synchronous. It is just syntactic sugar to make it look like "normal" sequential code. But while the result of the function call is awaited the event loop still continues in the background.

For example the following code executes foo() twice which will await a sleep. But even though it uses await the second function invokation will execute before the first one finishes. Ie. it runs in parallel.

import asyncio

async def main():
    print('started')
    await asyncio.gather(
        foo(),
        foo(),
    )

async def foo():
    print('starting foo')
    await asyncio.sleep(0.1)
    print('foo finished.')

asyncio.run(main())

prints:

started
starting foo
starting foo
foo finished.
foo finished.

await makes the call locally blocking, but the "wait" is transmitted through the async function (which is itself awaited), such that when it reaches the reactor the entire task can be moved to a waitlist and an other can be run instead.

Furthermore you do not need an await, you could also spawn the coroutine (to a separate task, which you may or may not wait on), or use one of the "future combinators" (asyncio.gather, asyncio.wait, ...) to run it concurrently with others.

Related