01
Overview
asyncio is async I/O framework. async def defines coroutines. await pauses. asyncio.run() runs event loop. Tasks for concurrent execution. gather for parallel. Prefer asyncio over threads for I/O-bound work.
bash
import asyncio
async def fetch(url):
await asyncio.sleep(1) # sim I/O
return f"data from {url}"
async def main():
results=await asyncio.gather(
fetch("a"), fetch("b"), fetch("c")
)
asyncio.run(main())02
Best Practices
Use async/await for I/O-bound (network, files). Use threads/processes for CPU-bound. asyncio.gather for parallel. asyncio.create_task to schedule. Use aiohttp for HTTP. Use anyio for asyncio/trio compat. Avoid blocking calls in async code.)
Ready to try asyncio?
Visit the official site for the latest version and full documentation.
Visit asyncio