Warm tip: This article is reproduced from serverfault.com, please click

Python: await the outer most async function

发布于 2020-12-02 06:13:20

Python coroutine created with 'async' keyword (Python 3.5+) can be awaited, however, the outer most one can't be awaited as Python says "SyntaxError: 'await' outside function"

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(await f())

How to 'await' the 'f' function in the example above?

Questioner
datdinhquoc
Viewed
0
HTF 2020-12-02 15:12:26

If you use Python 3.7+, the syntax is even simpler (no need to manually create a loop etc.):

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(aio.run(f())