Browse topics

asyncio.TaskGroup

Version
3.14
Since
3.11
Review
Draft

Summary#

asyncio.TaskGroup is an asynchronous context manager that waits for all of its tasks when the block exits. If a task raises an exception other than cancellation, the group cancels the remaining tasks and gathers failures into an exception group. KeyboardInterrupt and SystemExit are re-raised directly after the group waits for the cancelled tasks.

Syntax#

python
async def main():
    async with asyncio.TaskGroup() as group:
        task = group.create_task(coroutine())
    result = task.result()

Example#

python
import asyncio


async def fetch(name):
    await asyncio.sleep(0)
    return name.upper()


async def slow():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("slow task cancelled")
        raise


async def fail():
    raise ValueError("bad input")


async def main():
    async with asyncio.TaskGroup() as group:
        first = group.create_task(fetch("a"))
        second = group.create_task(fetch("b"))
    print(first.result(), second.result())

    try:
        async with asyncio.TaskGroup() as group:
            group.create_task(slow())
            group.create_task(fail())
    except* ValueError as errors:
        print([str(error) for error in errors.exceptions])


asyncio.run(main())

Expected output#

Text
A B
slow task cancelled
['bad input']

Common mistakes#

A plain except ValueError around the group does not catch the raised ExceptionGroup; use except*. Re-raise asyncio.CancelledError after cleanup. A coroutine that swallows it can make a task group misbehave.

Version applicability#

asyncio.TaskGroup and except* were added in Python 3.11, so the example requires 3.11 or later. Its asyncio.run call is available from Python 3.7.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0