Tasks (create_task) and gather
Why tasks
A Task is a scheduled coroutine.
- You create it
- The event loop runs it concurrently with others
create_task
create_task.py
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())create_task.py
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
gathergather is a convenient way to run many coroutines and collect results.
gather.py
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())gather.py
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
If one coroutine fails, gathergather cancels others by default.
You can keep errors as values:
gather_return_exceptions.py
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())gather_return_exceptions.py
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
Exercise 1 โ Create a Task
Exercise 2 โ Gather Multiple Tasks
Exercise 3 โ Task Name and Done
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
