Could someone please tell me What I am understanding wrong?

I am still learning the asyncio module in python 3.10. Below is a code I wrote trying to understand how to run coroutines as tasks on an event loop. the output I am getting is different from what I expected. Please help me understand why the output is what it is.

import asyncio 
    async def f(x):
            print(f"Inside f({x})...")
            await asyncio.sleep(x)
            print(f'slept for {x} seconds!!')
            return x
        except asyncio.CancelledError:  # Execute this part only when the task is cancelled.
    async def main():
        loop = asyncio.get_running_loop()
        task1 = loop.create_task(f(1), name="task1")
        task2 = loop.create_task(f(2), name="task2")
        task3 = loop.create_task(f(3), name="task3")

Inside f(1)…
Inside f(2)…
Inside f(3)…

I tried using asyncio.create_task() too, but the output is same in both cases.
I expect this code to cancel all the tasks and exit the main() immediately after the line print(task3.done()) is executed as I am not await ing any task .
But, the event loop runs the functionalities of f(1), f(2) and f(3) exactly one time before actually exiting (Hence those Inside f( ) messages in output).

My doubts are

  1. Why do all the tasks on the event loop in my code run once before getting cancelled?
  2. What is the execution order (if there is any, is it fixed or random?)

From my understanding

  1. asyncio.create_task schedules execution of f(x), which makes them running when main function is exiting, hence the cancels.
  2. Each of them is executed in order that is in code, up to the await asyncio.sleep(x). After that they continue asynchronously, and in theory (I believe) they are fairly checked upon if the task is finished.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.