TaskGroup

2 snippets in Python

PYPython

except* for Exception Groups

PY · Modern Features
syntax
try:
    ...
except* ErrorType as eg:
    ...
example
import asyncio

async def task_a():
    raise ValueError("bad value")

async def task_b():
    raise TypeError("wrong type")

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(task_a())
            tg.create_task(task_b())
    except* ValueError as eg:
        print(f"Value errors: {eg.exceptions}")
    except* TypeError as eg:
        print(f"Type errors: {eg.exceptions}")

# asyncio.run(main())
output
Value errors: (ValueError('bad value'),)
Type errors: (TypeError('wrong type'),)

Note except* can match multiple handlers for the same ExceptionGroup. It splits the group so each handler gets only its matching exceptions.

asyncio.TaskGroup (3.11+)

PY · Modern Features
syntax
async with asyncio.TaskGroup() as tg:
    tg.create_task(coro())
example
import asyncio

async def fetch(url: str) -> str:
    await asyncio.sleep(0.1)
    return f"Data from {url}"

async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(fetch("/api/users"))
        task2 = tg.create_task(fetch("/api/orders"))

    print(task1.result())
    print(task2.result())

# asyncio.run(main())
output
Data from /api/users
Data from /api/orders

Note TaskGroup replaces asyncio.gather() with structured concurrency. If any task raises, all other tasks are cancelled and errors are collected into an ExceptionGroup.