4. Use asyncio.TaskGroup for related tasks
Use asyncio.TaskGroup instead of managing related tasks manually.
Task groups make the lifetime of related concurrent work explicit and give failures structured semantics instead of leaving cancellation and cleanup spread across the call site. That usually makes async code easier to reason about because the tasks that belong together are created, awaited, and torn down in one block.
Note
Python 3.11+
4.1. Don’t do this
1tasks = [
2 asyncio.create_task(fetch_user()),
3 asyncio.create_task(fetch_orders()),
4]
5user, orders = await asyncio.gather(*tasks)
4.2. Do this
1async with asyncio.TaskGroup() as tg:
2 user_task = tg.create_task(fetch_user())
3 orders_task = tg.create_task(fetch_orders())
4
5user = user_task.result()
6orders = orders_task.result()