Structured Concurrency with asyncio.TaskGroup
`asyncio.gather()` easily leaks orphaned fire-and-forget tasks when one crashes. Python 3.11 introduced `asyncio.TaskGroup`: a structured context manager where if any task fails, all sibling tasks are cancelled and cleaned up before exiting the block 🛡️⚡.
import asyncio
async def fetch_user(uid):
await asyncio.sleep(0.01)
return f"User_{uid}"
async def main():
# Structured task lifecycle:
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch_user(101))
t2 = tg.create_task(fetch_user(102))
# Both guaranteed finished upon block exit:
print(t1.result(), t2.result())
asyncio.run(main())
# 22. Structured Concurrency with asyncio.TaskGroup Legacy asynchronous programming treated tasks like wild background threads. If Task B crashed, Task A kept running in the background indefinitely, silently leaking network sockets and memory 🛑. ```python import asyncio async def main(): async with asyncio.TaskGroup() as tg: t1 = tg.create_task(query_db()) t2 = tg.create_task(query_cache()) # Both tasks are strictly bounded to this lexical block! ``` ### Structured Concurrency Invariants 1. **Lexical Lifetime**: A task cannot outlive the `TaskGroup` context block that spawned it. 2. **Cascade Cancellation**: If any task in the group crashes, the context manager triggers `cancel()` on all other active sibling tasks in the group 🛡️. 3. **No Orphaned Execution**: You never have to wonder if a background job is still running after a function returns. --- ### Interactive Pop-Quiz 🧠 #### What happens if one child task raises an exception inside an `asyncio.TaskGroup` context? - [ ] All remaining sibling tasks in the group are immediately cancelled, and the error is raised upon block exit 🛡️ - [ ] The exception is ignored until all other tasks finish normally - [ ] The Python interpreter aborts with SIGSEGV - [ ] The failed task automatically restarts up to 3 times --- ### Practical Challenge 🎯 Use `asyncio.TaskGroup` to run two tasks: one returning `'ALPHA'` and one returning `'BETA'`. Await the context block exit, access the results via `.result()`, and print them concatenated with a dash (`'ALPHA-BETA'`). <details> <summary>Solution</summary> ```python import asyncio async def get_alpha(): await asyncio.sleep(0.01) return "ALPHA" async def get_beta(): await asyncio.sleep(0.01) return "BETA" async def main(): async with asyncio.TaskGroup() as tg: t1 = tg.create_task(get_alpha()) t2 = tg.create_task(get_beta()) print(f"{t1.result()}-{t2.result()}") asyncio.run(main()) ``` </details>