Keep Related Work Inside TaskGroup
Core idea
TaskGroup (Python 3.11+) is an async context manager for related tasks. Create tasks inside it; normal exit waits for all. A non-cancellation failure triggers cancellation of remaining tasks and, after cleanup, exceptions are grouped. Use except* to handle matching members of an ExceptionGroup. This provides a scoped lifetime for child tasks.
import asyncio
async def main(): async def job(x): return x*2 async with asyncio.TaskGroup() as group: a=group.create_task(job(3)) b=group.create_task(job(5)) print(a.result()+b.result())
asyncio.run(main())The group waits for both tasks before results are read.
Expected output:
16Cancel a sibling and clean up
import asyncio
async def main(): ready = asyncio.Event() async def worker(): try: ready.set() await asyncio.Event().wait() finally: print('cleaned') async def fail(): await ready.wait() raise ValueError('bad') try: async with asyncio.TaskGroup() as group: group.create_task(worker()) group.create_task(fail()) except* ValueError as errors: print(len(errors.exceptions))
asyncio.run(main())The failing task waits until its sibling is inside try. Cancellation runs finally before the group raises.
Expected output:
cleaned1Common mistake
Do not suppress CancelledError in child coroutines without a deliberate cancellation policy. TaskGroup relies on cancellation to close its scope. Do not schedule unrelated detached work inside a group and assume it is managed.
Practice
Add a second successful task to the first group and verify all results after exit. Explain how the failure example guarantees cleanup.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
TaskGroup
Check your understanding of taskgroup.
What is printed?
import asyncio
async def main(): async def f(): return 2 async with asyncio.TaskGroup() as g: t=g.create_task(f()) print(t.done(),t.result())
asyncio.run(main())What is printed?
import asyncio
async def main(): async def f(): raise ValueError('x') try: async with asyncio.TaskGroup() as g: g.create_task(f()) except* ValueError: print('caught')
asyncio.run(main())When is a successful group task guaranteed finished?
What happens to siblings on a non-cancellation failure?