Predict the output
The task is cancelled while sleeping. What's printed?
import asyncio
async def handler(log: list[str]) -> None:
try:
await asyncio.sleep(10)
finally:
log.append("released")
async def main() -> None:
log: list[str] = []
t = asyncio.create_task(handler(log))
await asyncio.sleep(0.01)
t.cancel()
try:
await t
except asyncio.CancelledError:
log.append("cancelled")
print(log)
asyncio.run(main())Hint 1 of 1
What runs as the exception passes through?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['released', 'cancelled']
Correct. finally runs as CancelledError passes through, then the awaiting code sees it.
cancel() makes the task's current await raise CancelledError. The handler's finally runs first, cleaning up, and the error then reaches whoever awaits the task.
Why not the others?
- B
['cancelled']. finally always runs. - C
['released']. Awaiting the cancelled task raises CancelledError. - D
[]. Both appends run.