Tasks (create_task) and gather
Why tasks
Section titled “Why tasks”A Task is a scheduled coroutine.
- You create it
- The event loop runs it concurrently with others
create_task
Section titled “create_task”import asyncio
async def job(i: int) -> str:
await asyncio.sleep(0.2)
return f"done {i}"
async def main():
t1 = asyncio.create_task(job(1))
t2 = asyncio.create_task(job(2))
# await results
print(await t1)
print(await t2)
asyncio.run(main())asyncio.gather
Section titled “asyncio.gather”gather is a convenient way to run many coroutines and collect results.
import asyncio
async def job(i: int) -> int:
await asyncio.sleep(0.1)
return i * i
async def main():
results = await asyncio.gather(*(job(i) for i in range(10)))
print(results)
asyncio.run(main())Error behavior
Section titled “Error behavior”If one coroutine fails, gather cancels others by default.
You can keep errors as values:
import asyncio
async def ok():
return 1
async def bad():
raise ValueError("boom")
async def main():
res = await asyncio.gather(ok(), bad(), return_exceptions=True)
print(res)
asyncio.run(main())🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Task
Section titled “Exercise 1 – Create a Task”Exercise 2 – Gather Multiple Tasks
Section titled “Exercise 2 – Gather Multiple Tasks”Exercise 3 – Task Name and Done
Section titled “Exercise 3 – Task Name and Done”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading