← Back to Python, page 4

python-0061 · Hard senior

Handle cancellation, timeouts and errors in asyncio with TaskGroup and timeout.

asyncio.TaskGroup runs tasks as a unit: if one fails, the others are cancelled and the errors are raised together as an ExceptionGroup, handled with except*. asyncio.timeout bounds how long a block may take and raises TimeoutError. Cancelled tasks receive CancelledError at their current await and should clean up in finally.

Full answer
python
import asyncio

async def job(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ValueError(f"{name} failed")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled, cleaning up")
        raise

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(job("slow", 1.0))
            tg.create_task(job("bad", 0.05, fail=True))
    except* ValueError as eg:
        print("errors:", [str(e) for e in eg.exceptions])
    try:
        async with asyncio.timeout(0.05):
            await job("too-long", 1.0)
    except TimeoutError:
        print("timed out")

asyncio.run(main())

Output:

text
slow cancelled, cleaning up
errors: ['bad failed']
too-long cancelled, cleaning up
timed out

When 'bad' raises, the TaskGroup cancels 'slow', which prints its cleanup message and re-raises CancelledError as it should, and then the group raises an ExceptionGroup containing the ValueError. except* picks out the ValueErrors. asyncio.timeout (Python 3.11+) cancels the awaited job after 0.05 seconds, so its own cleanup message prints first, and converts the cancellation into TimeoutError at the block boundary. Swallowing CancelledError breaks this machinery, so always re-raise it after cleanup.

python
import asyncio

async def job(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ValueError(f"{name} failed")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled, cleaning up")
        raise

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(job("slow", 1.0))
            tg.create_task(job("bad", 0.05, fail=True))
    except* ValueError as eg:
        print("errors:", [str(e) for e in eg.exceptions])
    try:
        async with asyncio.timeout(0.05):
            await job("too-long", 1.0)
    except TimeoutError:
        print("timed out")

asyncio.run(main())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • TaskGroup cancels siblings on failure
  • Errors arrive as an ExceptionGroup
  • except* handles groups
  • asyncio.timeout bounds a block
  • Re-raise CancelledError after cleanup

Common mistakes

  • Catching and swallowing CancelledError
  • Using gather without handling partial failures

Follow-ups

  • How does asyncio.shield work?
  • How would you limit concurrency to 10 tasks?

Tips

  • Show the cancelled sibling