Show contents
Chapter 5 of 7 · 20 min
Asynchronous programming with asyncio
By the end of this chapter, you'll be able to
- Explain the difference between waiting (I/O) and computing (CPU)
- Understand the role of the event loop and of await
- Write coroutines with async/await and run them with asyncio.gather
- Know when async doesn't help: heavy calculations
Waiting without blocking
Input/output (I/O) means waiting for something external: the network, the disk, a database. During that wait, the processor does nothing. The idea of async: when a task has to wait, it gives control back, and another task makes progress in the meantime.
You already know the tool that lets you "pause" a function: the generator. Here's a mini event loop that moves several downloads forward in turn. Each yield means "I have to wait, pass control on":
from collections import deque
def download(name, chunks):
for i in range(1, chunks + 1):
print(f"{name}: chunk {i}/{chunks}")
yield # "I have to wait for the network: pass control on"
return f"{name} done"
def loop(tasks):
queue = deque(tasks)
while queue:
task = queue.popleft()
try:
next(task)
queue.append(task)
except StopIteration as end:
print("→", end.value)
loop([download("photo", 2), download("video", 3)])
photo: chunk 1/2
video: chunk 1/3
photo: chunk 2/2
video: chunk 2/3
→ photo done
video: chunk 3/3
→ video done
The two tasks interleave without any thread: it's cooperative concurrency. Each task decides itself when to give control back. asyncio does exactly this, with real handling of the network and timers.
The loop restarts A exactly where it stopped.
Text description of the animation
- Task A starts and sends its request.
- A reaches an await: it gives control back to the loop instead of blocking.
- The loop moves B forward, which sends its own request while A waits.
- The network signals that A's response is available.
- The loop restarts A exactly where it stopped.
async and await
With asyncio, a function declared async def is a coroutine. Inside it, await marks the points where it can wait without blocking the others. This code runs on your computer (the labs on this site don't have a real asyncio loop):
import asyncio
import time
async def weather(city: str, delay: float) -> str:
await asyncio.sleep(delay) # simulates waiting for a remote service
return f"{city}: response in {delay} s"
async def main() -> None:
start = time.perf_counter()
results = await asyncio.gather(
weather("Dakar", 1.0),
weather("Lima", 1.0),
weather("Hanoi", 1.0),
)
for r in results:
print(r)
print(f"Total time: {time.perf_counter() - start:.1f} s")
asyncio.run(main())
Dakar: response in 1.0 s
Lima: response in 1.0 s
Hanoi: response in 1.0 s
Total time: 1.0 s
asyncio.run(main())creates the event loop and runs the main coroutine;asyncio.gather(...)starts several coroutines together and waits until they're all finished. The results arrive in the order of the arguments;- three one-second waits take one second in total, not three.
For real HTTP requests, you use an asynchronous library, such as httpx.AsyncClient. The principle stays the same: await client.get(url).
When async doesn't help
Async speeds up programs that wait. It doesn't speed up calculations: a loop doing millions of operations never gives control back, and blocks every other task in the meantime. To spread a heavy calculation over several processor cores, you use processes (concurrent.futures.ProcessPoolExecutor).
| The program spends its time… | Suitable tool |
|---|---|
| waiting for the network or the disk | asyncio (or threads) |
| computing | several processes |
Your turn
Worked exercise
Worked exercise: a loop that prioritises the shortest task
Change the mini event loop so that it finishes first the tasks with the fewest chunks left. At each yield, each task produces the number of chunks it has left. Use heapq to always move forward the task closest to the end. With a 3-chunk video and a 2-chunk photo, the photo must finish first.
Hint 1
(left, number, task) in the heap: the number breaks ties, because Python can't compare two generators.Hint 2
next(task) gives the number of chunks left before the first chunk. After each next, put the task back in the heap with its new value.Show the solution and common mistakes
import heapq
def download(name, chunks):
for i in range(1, chunks + 1):
yield chunks - i + 1
print(f"{name}: chunk {i}/{chunks}")
return f"{name} done"
def priority_loop(tasks):
heap = []
for number, task in enumerate(tasks):
heapq.heappush(heap, (next(task), number, task))
while heap:
_, number, task = heapq.heappop(heap)
try:
heapq.heappush(heap, (next(task), number, task))
except StopIteration as end:
print("→", end.value)
priority_loop([download("video", 3), download("photo", 2)])
photo: chunk 1/2
photo: chunk 2/2
→ photo done
video: chunk 1/3
video: chunk 2/3
video: chunk 3/3
→ video done
Common mistakes:
- Storing
(left, task)without a number: on a tie, Python tries to compare two generators and raises aTypeError. - Forgetting to put the task back in the heap after
next: it stops halfway and never finishes.
Summary
- 1Async speeds up programs that wait (network, disk), not calculations.
- 2An event loop moves forward in turn the tasks that give control back.
- 3async def creates a coroutine; await marks a non-blocking wait point.
- 4asyncio.gather starts several coroutines together; asyncio.run starts the loop.
- 5A blocking call (time.sleep, requests) in a coroutine freezes the whole loop.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.