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.

Frequently asked questions

How does Python handle TaskGroup?
Python covers this with 2 copy-ready snippets on this page. The "except* for Exception Groups" snippet in Python uses `try:`.
Which code does the Python example use?
The "except* for Exception Groups" snippet uses `try:`, from the Modern Features section of the Python cheat sheet.
What other Python snippets are shown for "TaskGroup"?
Besides "except* for Exception Groups", this page also shows "asyncio.TaskGroup (3.11+)".
Is there anything to watch out for?
Yes. For "except* for Exception Groups": except* can match multiple handlers for the same ExceptionGroup. It splits the group so each handler gets only its matching exceptions.