Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Asynchrony and concurrency

An event loop interleaves tasks when the running coroutine suspends while waiting for a result.

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

Syntax

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

An event loop interleaves tasks when the running coroutine suspends while waiting for a result.

Calling a coroutine function creates a coroutine. TaskGroup schedules it as a task and waits for children at exit. An ordinary child exception cancels siblings and is reported in an exception group after cleanup.

The results [4, 9] follow the task list order after the group exits.

import asyncio
async def demo():
    ready=asyncio.Event()
    cleaned=[]
    async def waiter():
        try:
            ready.set()
            await asyncio.Event().wait()
        finally: cleaned.append(1)
    async def fail():
        await ready.wait()
        raise ValueError('bad')
    try:
        async with asyncio.TaskGroup() as group:
            group.create_task(waiter())
            group.create_task(fail())
    except* ValueError: pass
    assert cleaned==[1]
asyncio.run(demo())

Examples

import asyncio

async def square(n):
    await asyncio.sleep(0)
    return n * n

async def main():
    async with asyncio.TaskGroup() as group:
        tasks = [group.create_task(square(n)) for n in (2, 3)]
    print([t.result() for t in tasks])

asyncio.run(main())

Result

[4, 9]

The results [4, 9] follow the task list order after the group exits.

Sources