AsyncIO Checkpoint
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This checkpoint covers the whole module: coroutines and the event loop, tasks and gather, timeouts and cancellation, and async HTTP with blocking code. Predict each output before you read the answer.
Choose the tool
A service must check 2000 product pages over HTTP, then resize 20 large images. The page checks wait on the network, so use asyncio with a limit. The resizing uses the CPU, so use processes.
Asyncio makes waiting cheap. It does not make calculation faster, and one blocking call stalls every task.
Make every wait bounded
Every awaited call should have a timeout, and every failure should become a value or a clear error. Use gather with a Semaphore, and cancel what you no longer need.
Example 1 · A bounded batch of checks
import asyncio
async def check(url): await asyncio.sleep(0.5 if "down" in url else 0.01) return "up"
async def safe(sem, url): async with sem: try: return url, await asyncio.wait_for(check(url), 0.1) except TimeoutError: return url, "timeout"
async def main(): sem = asyncio.Semaphore(3) urls = ["/home", "/down", "/cart", "/pay"] results = await asyncio.gather(*(safe(sem, u) for u in urls)) print(dict(results))
asyncio.run(main()){'/home': 'up', '/down': 'timeout', '/cart': 'up', '/pay': 'up'}What this code does
- Each check has its own timeout, so
/downends as"timeout"and does not hold the others. - A Semaphore of 3 caps the load, and
gatherkeeps the order.
Example 2 · Cancel what is no longer needed
import asyncio
async def lookup(name, delay): await asyncio.sleep(delay) return name
async def main(): tasks = [asyncio.create_task(lookup("primary", 0.01)), asyncio.create_task(lookup("backup", 0.5))] done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for t in pending: t.cancel() print(next(iter(done)).result(), "won;", len(pending), "cancelled")
asyncio.run(main())primary won; 1 cancelled
What this code does
waitreturns when the first task is done.- The slow backup is cancelled so it stops using resources.
Print results from gather or sorted data, never from the order tasks happen to finish.
Finish up
Mark this lesson complete
This is the last lesson in this section.