Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.TaskGroup

Manages related asynchronous tasks in a scope that waits for every member when it exits.

Version: Python 3.14; repository image, production runtime not attested

Syntax

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

Manages related asynchronous tasks in a scope that waits for every member when it exits.

On normal exit all members are finished, though a cancelled member can still raise CancelledError when its result is requested. A failing member ordinarily triggers cancellation of the remaining group members.

Add related coroutines with group.create_task. Leaving the context waits for every child, so successful results are ready afterwards. The first ordinary failure cancels siblings; after cleanup the group raises the failures in an ExceptionGroup or BaseExceptionGroup. A child cancellation alone does not trigger this policy. KeyboardInterrupt and SystemExit are re-raised specially. A group can exit normally with a cancelled child. Calling that child's result() then raises CancelledError.

import asyncio
async def main():
    async def fail():
        raise ValueError("group")
    try:
        async with asyncio.TaskGroup() as tg:
            sibling = tg.create_task(asyncio.Event().wait())
            tg.create_task(fail())
    except* ValueError as errors:
        assert len(errors.exceptions) == 1
    assert sibling.cancelled()
asyncio.run(main())
import asyncio
async def main():
    async with asyncio.TaskGroup() as group:
        child = group.create_task(asyncio.Event().wait())
        child.cancel()
    assert child.cancelled()
    try:
        child.result()
    except asyncio.CancelledError:
        pass
    else:
        raise AssertionError
asyncio.run(main())

Examples

import asyncio

async def main():
    async with asyncio.TaskGroup() as group:
        first = group.create_task(asyncio.sleep(0, result=3))
        second = group.create_task(asyncio.sleep(0, result=8))
    print(first.result() + second.result())

asyncio.run(main())

Result

11

Add related coroutines with group.create_task. Leaving the context waits for every child, so successful results are ready afterwards. The first ordinary failure cancels siblings; after cleanup the group raises the failures in an ExceptionGroup or BaseExceptionGroup. A child cancellation alone does not trigger this policy. KeyboardInterrupt and SystemExit are re-raised specially. A group can exit normally with a cancelled child. Calling that child's result() then raises CancelledError.

Sources