Python asyncio TaskGroup Batch Runner

Run coroutines in an asyncio.TaskGroup so the first failure cancels siblings, then inspect the raised ExceptionGroup.

PythonResilience

Code

pythonsnippet
36 lines
import asyncio
from dataclasses import dataclass


@dataclass
class Job:
    name: str
    seconds: float


async def run_job(job: Job) -> tuple[str, str]:
    await asyncio.sleep(job.seconds)
    if job.name == "bad":
        raise RuntimeError(f"job {job.name} failed")
    return job.name, "ok"


async def run_batch(jobs: list[Job]) -> dict[str, str]:
    tasks: list[tuple[str, asyncio.Task[tuple[str, str]]]] = []
    async with asyncio.TaskGroup() as group:
        for job in jobs:
            tasks.append((job.name, group.create_task(run_job(job))))
    return {name: task.result()[1] for name, task in tasks}


async def main() -> None:
    print(await run_batch([Job("alpha", 0.05), Job("beta", 0.01)]))
    try:
        await run_batch([Job("slow", 1.0), Job("bad", 0.01)])
    except* RuntimeError as group:
        print("failures:", [str(error) for error in group.exceptions])
        print("slow job cancelled by TaskGroup")


asyncio.run(main())

How it works

Under the hood: the class class and the functions run_job, run_batch and main.

Repetition is confined to for job in jobs — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. The import line is the dependency contract: dataclass comes from asyncio and nothing else. RuntimeError is the guard’s signal — thrown at the branch, before any partial work happens.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • Requires asyncio as a package; the snippet will not run without it.
  • The guard job.name == "bad" short-circuits the flow with an early raise when its condition holds.

Using it

The primary signature is def run_job(job: Job) -> tuple[str, str]

The demo output is labeled (failures:, slow job cancelled by TaskGroup), so every printed line maps back to its originating operation.

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

Key statements

async def main() -> None:
    print(await run_batch([Job("alpha", 0.05), Job("beta", 0.01)]))
    try:
        await run_batch([Job("slow", 1.0), Job("bad", 0.01)])
    except* RuntimeError as group:
        print("failures:", [str(error) for error in group.exceptions])
        print("slow job cancelled by TaskGroup")
return {name: task.result()[1] for name, task in tasks}
async def run_job(job: Job) -> tuple[str, str]:
    await asyncio.sleep(job.seconds)
    if job.name == "bad":
        raise RuntimeError(f"job {job.name} failed")
    return job.name, "ok"

Interactive Tools for This Topic

FAQ

Does `run_job` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What happens if the preconditions do not hold?
The code throws `RuntimeError` — the guard `job.name == "bad"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does this require external packages?
Yes — `asyncio`. Add it to your project before running the snippet.