I'm trying to understand this code:
async def delay(sec: int):
print(f"delay() going to sleep for {sec}s")
await asyncio.sleep(sec)
print("delay() waked up")
async def main():
task = asyncio.create_task(delay(5))
seconds_elapsed = 0
while not task.done():
print(f"checking task finished... {task.done()}")
await asyncio.sleep(1)
seconds_elapsed += 1
if seconds_elapsed == 3:
print(f"cancelled result: {task.cancel()}")
print(f"task is done: {task.done()}")
print("main() awaiting task")
try:
# await task
pass
except asyncio.CancelledError:
print("task was cancelled")
print("main() finished")
asyncio.run(main())
The logs:
checking task finished... False
delay() going to sleep for 5s
checking task finished... False
checking task finished... False
cancelled result: True
task is done: False
checking task finished... False
main() awaiting task
main() finished
After 3s has passed, the task was canceled and the task.done() is still false, so the while loop continues with line 15... finally the while loop break at line 16 and print line 22.
Pls help me to explain why? I thought that the while loop should run forever because the task.done() will always be false.