Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 8 · Async correctness patternsasyncio.TaskGroup — structured concurrency (3.11+) replaces gatherpredict132 / 161
+150 XP
Task
📝 **Task:** Predict the exact 6-line output. Three tasks are spawned inside a TaskGroup: ok-fast (10ms, no fail), boom (20ms, raises ValueError), ok-slow (50ms, no fail). The TaskGroup catches the boom exception and prints a summary. Trace which task lines actually fire and which get cancelled mid-sleep. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

import asyncio


events: list[str] = []


async def task(name: str, work: float, fail: bool = False) -> None:
    events.append(f"{name} start")
    await asyncio.sleep(work)
    if fail:
        events.append(f"{name} raising")
        raise ValueError(f"{name} failed")
    events.append(f"{name} done")


async def main() -> None:
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(task("ok-fast", 0.01))
            tg.create_task(task("boom", 0.02, fail=True))
            tg.create_task(task("ok-slow", 0.05))
    except* ValueError as eg:
        events.append(f"caught {len(eg.exceptions)} exception(s)")

    for e in events:
        print(e)


asyncio.run(main())

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…