Sub topic 2
Running coroutines concurrently as tasks
Assume you know Python functions, async/await, exceptions, and the difference between I/O-bound and CPU-bound work. This chapter uses Python 3.11 or later for TaskGroup.
Running coroutines concurrently as tasks
A coroutine is a function that can pause at await. A task schedules a coroutine on the event loop so it can run while other tasks wait for I/O.
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} finished"
async def main():
first = asyncio.create_task(fetch("first", 1))
second = asyncio.create_task(fetch("second", 1))
print(await first)
print(await second)
asyncio.run(main())Both tasks start before either result is awaited. They finish after about one second, not two, because asyncio.sleep gives control back to the event loop.
Collecting results with `asyncio.gather`
Use asyncio.gather when you want to start several awaitables and collect their results in input order.
results = await asyncio.gather(
fetch("A", 0.2),
fetch("B", 0.1),
)
print(results) # ['A finished', 'B finished']The shorter operation finishes first, but the result list keeps the order passed to gather.
> callout note > Concurrency helps I/O-bound work. It does not make CPU-heavy Python code run in parallel on one event-loop thread.
Structured concurrency with `TaskGroup`
TaskGroup groups related tasks inside a context. The block does not exit until its tasks finish. If one task fails, the group cancels its remaining tasks and reports the failure.
async def main():
try:
async with asyncio.TaskGroup() as group:
group.create_task(fetch("A", 0.2))
group.create_task(fetch("B", 0.1))
except* ValueError as errors:
print("handled:", errors)Handling errors across tasks
By default, gather propagates an exception. With return_exceptions=True, it places exceptions in the result list. A TaskGroup raises an ExceptionGroup, which you can select with except*.
Cancelling tasks safely
Calling task.cancel() requests cancellation. At the next suspension point, the task receives asyncio.CancelledError. Clean up resources, then usually re-raise the exception.
async def worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("cleaning up")
raiseExercise
Which tool should you prefer when related tasks must finish as one unit and failures should cancel their siblings?
Show answer
Use asyncio.TaskGroup.