python async-await blocking understanding

25 views Asked by At

I'm new to async-await and this has been confusing me.

import asyncio

# Step 1: Define an asynchronous function
async def print_message(message, delay):
    await asyncio.sleep(delay)
    print(message)

# Step 2: Define the main asynchronous function
async def main():
    # Step 3: Create tasks without gather()
    task1 = asyncio.create_task(print_message("Hello", 2))
    task2 = asyncio.create_task(print_message("Async", 1))
    task3 = asyncio.create_task(print_message("World", 3))

    # Step 4: Await tasks individually
    await task1
    await task2
    await task3
    print("does this print before tasks?")

# Step 5: Run the main asynchronous function in an event loop
if __name__ == "__main__":
    asyncio.run(main())

So here in the main coroutine, three asynchronous tasks are created and handed off to the event loop. And these tasks are awaited in the same order, i.e. task1, task2, and task3.

Logically, since task2 has lower delay this Async will get displayed earlier.

But I thought await keyword will hold the execution of task1 before it can move further down to task2 and task3.

  1. So my expectation was that the prints will also be in the same order irrespective of the delay value.

  2. Also finally I've added a print in the main itself after awaits. So while these awaits are holding, shouldn't this print be executed?

0

There are 0 answers