Async / Await
Python · Advanced
Definition
asyncio runs many I/O tasks concurrently in one thread using coroutines with async and await.
Speeds up network-heavy programs like scrapers and APIs.
Diagram
Flowchart
Example: Concurrent tasks
import asyncio
async def job(n):
await asyncio.sleep(0.01)
return n * 2
async def main():
print(await asyncio.gather(job(1), job(2), job(3)))
asyncio.run(main())Output: [2, 4, 6]
Key points
- Great for I/O, not CPU work
- Use multiprocessing for CPU-bound tasks
Interview questions
Threading vs asyncio?
Threads are OS-scheduled; asyncio switches cooperatively at await points.