Asyncio Taskgroup With Timeout

Use asyncio.TaskGroup with timeout for structured concurrency and automatic cancellation on failure.

PythonResilience

Code

pythonsnippet
9 lines
import asyncio
async def run_with_timeout(tasks, timeout=30):
    async with asyncio.timeout(timeout):
        async with asyncio.TaskGroup() as tg:
            results = []
            for task in tasks:
                t = tg.create_task(task())
                results.append(t)
            return [t.result() for t in results]

How the snippet works

Structurally, expect the function run_with_timeout and nothing else.

Repetition is confined to for task in tasks — the rest of the file is straight-line. Await points sequence the coroutines; a failure lands where the result is consumed.

The result is a fresh construction, so callers can keep their originals.

Watch out for

  • Plan for an install step: asyncio is a real dependency, resolved by the package manager.

Using it

The primary signature is def run_with_timeout(tasks, timeout=30)

run_with_timeout is what another module would consume; nothing else here is load-bearing for callers.

Key statements

async def run_with_timeout(tasks, timeout=30):
    async with asyncio.timeout(timeout):
        async with asyncio.TaskGroup() as tg:
            results = []
            for task in tasks:
                t = tg.create_task(task())
                results.append(t)
            return [t.result() for t in results]

Interactive Tools for This Topic

FAQ

Does `run_with_timeout` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Do I need to install anything before running this?
Yes: `asyncio` must be present in the project or the import fails at load time.