async and await
async def defines a coroutine — a function that can pause at each await while it waits for something, letting other coroutines run in the meantime. asyncio.run() starts the event loop, and asyncio.gather() or a TaskGroup runs many coroutines concurrently in a single thread. Async shines when a program handles hundreds or thousands of network connections.
Your first coroutine
import asyncio
async def greet(name: str, delay: float) -> str:
await asyncio.sleep(delay) # pause here; others may run
return f"Hello, {name}"
async def main() -> None:
message = await greet("Ana", 0.5)
print(message)
asyncio.run(main())Hello, Ana
- Calling
greet(...)doesn't run it; it creates a coroutine object. awaitruns a coroutine and waits for its result — only allowed insideasync def.asyncio.run(main())starts the event loop: the scheduler that switches between coroutines.
Running many at once
import asyncio
import time
async def fetch(url: str) -> str:
await asyncio.sleep(1) # pretend network call
return f"data from {url}"
async def main() -> None:
start = time.perf_counter()
results = await asyncio.gather(
fetch("a.com"), fetch("b.com"), fetch("c.com")
)
print(results)
print(f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())['data from a.com', 'data from b.com', 'data from c.com'] 1.0s
Three one-second waits finish in one second, all in a single thread. gather returns results in the order you passed the coroutines.
TaskGroup: structured and safe
import asyncio
async def job(name: str, seconds: float) -> str:
await asyncio.sleep(seconds)
return name
async def main() -> None:
async with asyncio.TaskGroup() as tg:
slow = tg.create_task(job("report", 0.3))
fast = tg.create_task(job("email", 0.1))
print(fast.result(), slow.result())
asyncio.run(main())email report
A TaskGroup (Python 3.11+) waits for every task when the block ends. If one task fails, the others are cancelled and the error is raised — no forgotten background tasks.
Timeouts
import asyncio
async def slow_api() -> str:
await asyncio.sleep(5)
return "finally"
async def main() -> None:
try:
async with asyncio.timeout(1):
print(await slow_api())
except TimeoutError:
print("Gave up after 1 second")
asyncio.run(main())Gave up after 1 second
Limiting concurrency
import asyncio
limit = asyncio.Semaphore(3) # at most 3 at a time
active = 0
peak = 0
async def call_api(i: int) -> int:
global active, peak
async with limit:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.1)
active -= 1
return i * 2
async def main() -> None:
results = await asyncio.gather(*(call_api(i) for i in range(10)))
print(sum(results), "peak concurrency:", peak)
asyncio.run(main())90 peak concurrency: 3
Threads or async?
| Threads | asyncio | |
|---|---|---|
| Best for | Tens of I/O tasks, existing sync libraries | Hundreds to thousands of connections |
| Libraries | Any (requests, database drivers) | Async ones (httpx, asyncpg) |
| Switching | The OS decides, at any moment | Only at await, so fewer race conditions |
| Used by | Scripts, data jobs | FastAPI, chat servers, LLM streaming |
Practice
Estimate the gain from async. Given call durations durations = [1.2, 0.4, 0.9, 0.3] (seconds), print the total time if you await them one by one, then the time with gather (they overlap, so it's the slowest one). Round both to 1 decimal.
2.8 1.2