Async / Await
What asyncio does
asyncio runs many waiting tasks on a single thread. While one task waits for the network, others keep working. It's ideal for thousands of API calls, chat servers or web scrapers.
Key words
async defdefines a coroutine (a function that can pause).awaitpauses here until the awaited thing finishes, letting other tasks run.asyncio.run(main())starts the event loop from normal code.asyncio.gather(a(), b(), c())runs coroutines concurrently and collects the results.asyncio.create_task()starts something in the background.
Rules of thumb
- Use
await asyncio.sleep(), nevertime.sleep(), inside async code;time.sleepblocks everything. - Async only helps I/O-bound work. CPU-heavy code still needs multiprocessing.
- Use async libraries (
httpx,aiohttp) for HTTP inside async code.
💡 In this app, the code already runs inside an event loop, so call await main() instead of asyncio.run(main()).
▶️ Runs in the app (with await main()).
Example
import asyncio
import time
async def fetch(item_id):
await asyncio.sleep(1) # pretend network wait
return f"item {item_id}"
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
print(results) # ['item 1', 'item 2', 'item 3']
print(f"{time.perf_counter() - start:.1f}s") # ~1.0s, not 3s
# On a computer:
asyncio.run(main())
# In this app's editor, use this line instead:
# await main()