Python Glossary Русский

Python 3.11+Async programmingterm

asyncio.TaskGroup

tasks

An asynchronous context manager for a group of tasks: the async with block does not exit until every task finishes, and one failure cancels the rest.

Syntax

async with asyncio.TaskGroup() as tg: task = tg.create_task(coro)

Unlike asyncio.gather(), after the first error the sibling tasks do not keep running in the background — they are cancelled; what escapes is not the exception itself but an ExceptionGroup holding every error, so you catch it with except* and a plain except ValueError misses it. Read results from the saved tasks (task.result()) after the block. Adding tasks to a group that has exited raises RuntimeError.

Examples

import asyncio
async def square(n):
    await asyncio.sleep(0.01)
    return n * n
async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(square(n)) for n in (2, 3, 4)]
    print([t.result() for t in tasks])  # → [4, 9, 16]
asyncio.run(main())
import asyncio
async def bad():
    await asyncio.sleep(0.01)
    raise ValueError('сбой')
async def slow():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print('slow отменена')  # → slow отменена
        raise
async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(bad())
            tg.create_task(slow())
    except* ValueError as eg:
        print(type(eg).__name__, eg.exceptions)  # → ExceptionGroup (ValueError('сбой'),)
asyncio.run(main())

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy