Home > Software engineering >  async function in Python not working as expected
async function in Python not working as expected

Time:02-14

I have the following code snippet:

import asyncio

def main():
    asyncio.run(work())
    print("BEFORE")

async def work():
    await asyncio.sleep(1)
    print("AFTER")

main()

I would like "BEFORE" to be printed first, followed by "AFTER" however this prints "AFTER" first instead - have I misunderstood how async functions work? I thought that running asyncio.run(...) would allow my code to skip to print("BEFORE") while still running work() in the background.

Ideal output is:

BEFORE
AFTER

Right now it's

AFTER
BEFORE

CodePudding user response:

run seems to be blocking, so you might want to just use gather here:

import asyncio

async def main():
    await asyncio.gather(work(), setup())
    print('After gather')

async def work():
    await asyncio.sleep(2)
    print("AFTER")

async def setup():
    print("BEFORE")

asyncio.run(main())

This correctly prints

BEFORE
AFTER
After gather

The entire gather statement itself is blocking as well, but all of the functions specified in the gather statement can run asynchronously.

CodePudding user response:

According to the documentation:

The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)

The asyncio.run should be the entry point, not used for starting a background job. So it does not skip to print("BEFORE").

  • Related