Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Module asyncio

Coordinate asynchronous I/O with an event loop, coroutines and tasks.

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

Syntax

asyncio.run(main())

Coordinate asynchronous I/O with an event loop, coroutines and tasks.

Calling a coroutine function creates a coroutine object without starting its body. TaskGroup schedules related work and waits for its tasks on exit.

A non-cancellation failure in a child causes cancellation of remaining children and ordinary failures are reported in an ExceptionGroup.

Examples

import asyncio

async def work(value):
    await asyncio.sleep(0)
    return value * 2

async def main():
    async with asyncio.TaskGroup() as group:
        tasks = [group.create_task(work(v)) for v in (2, 5)]
    print([t.result() for t in tasks])
    async def broken():
        raise ValueError("child")
    try:
        async with asyncio.TaskGroup() as group:
            group.create_task(broken())
    except* ValueError as errors:
        print(len(errors.exceptions))

asyncio.run(main())

Result

[4, 10]
1

A non-cancellation failure in a child causes cancellation of remaining children and ordinary failures are reported in an ExceptionGroup.

Sources