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):
try:
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.
print(f'Cancelled({x})')
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")
print(task1.done())
print(task2.done())
print(task3.done())
asyncio.run(main())
Output:
False
False
False
Inside f(1)…
Inside f(2)…
Inside f(3)…
Cancelled(3)
Cancelled(1)
Cancelled(2)
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
- Why do all the tasks on the event loop in my code run once before getting cancelled?
- What is the execution order (if there is any, is it fixed or random?)