When writing async code in Python, it's common to have multiple independent tasks that can run concurrently. The asyncio module provides two handy methods for running async tasks in parallel: asyncio.gather() and asyncio.create_task().
asyncio.gather() for Bundling Tasks
import asyncio
async def task1():
print('Task 1 running')
await asyncio.sleep(1)
return 'result 1'
async def task2():
print('Task 2 running')
await asyncio.sleep(2)
return 'result 2'
async def main():
results = await asyncio.gather(
task1(),
task2()
)
print(results)
asyncio.run(main())
This runs
The key benefit of
asyncio.create_task() for Unblocked Execution
import asyncio
async def main():
task1 = asyncio.create_task(task1())
await do_other_work()
await task1
Here
So in summary,
Using these tools together enables complex concurrent async logic in Python. Just be careful to