Predict the output
One of two tasks fails. What's printed?
import asyncio
async def ok(log: list[str]) -> None:
try:
await asyncio.sleep(1)
log.append("ok finished")
except asyncio.CancelledError:
log.append("ok cancelled")
raise
async def bad() -> None:
raise ValueError("boom")
async def main() -> None:
log: list[str] = []
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(ok(log))
tg.create_task(bad())
except* ValueError:
log.append("caught")
print(log)
asyncio.run(main())Hint 1 of 1
What does a TaskGroup do to siblings when one fails?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['ok cancelled', 'caught']
Correct. The group cancels the sibling, then raises an ExceptionGroup that except* catches.
When one task in a TaskGroup fails, the group cancels the others and waits for them before leaving. ok logs its cancellation and re-raises, then the group raises an ExceptionGroup that except* matches.
Why not the others?
- B
['ok finished', 'caught']. TaskGroup cancels siblings on failure. - C
['caught']. The cancelled sibling logs before re-raising. - D It crashes with ValueError. except* ValueError handles it.