Writing efficient coroutines is key to maximizing the benefits of Asyncio. Here are some best practices:
await
for I/O-bound tasks to keep the event loop running smoothly.asyncio.gather
for Concurrency: When you need to run multiple coroutines concurrently, use asyncio.gather
to manage and await them together.import asyncio
async def io_bound_task():
await asyncio.sleep(1)
return "Task completed"
async def main():
results = await asyncio.gather(io_bound_task(), io_bound_task(), io_bound_task())
print(results)
asyncio.run(main())
import asyncio
async def safe_task():
try:
await asyncio.sleep(1)
raise ValueError("An error occurred")
except ValueError as e:
print(f"Caught exception: {e}")
asyncio.run(safe_task())
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://example.com'] * 5
results = await asyncio.gather(*(fetch(url) for url in urls))
print(results)
asyncio.run(main())