Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
What you will learn
- Tell waiting from working, and know which one async helps
- Explain what async def returns, what asyncio.run starts and what await does
- Run several waits together with asyncio.gather and TaskGroup
- Spot a forgotten await and a blocking time.sleep on the event loop
Before you start
- Python functions and return values
- Generators and yield
- The with statement
So far your programs have done one thing, finished it, then moved on. But plenty of programs spend most of their time waiting on something else, like a website, a database or an AI model. Async is how Python makes good use of that waiting.
Think about one cook with three pots to make. Each pot has to simmer, and while it simmers the cook has nothing to do. That's waiting. A cook who stares at each pot until it's done, then starts the next, takes three times as long. A smarter cook puts the first pot on, walks away, puts on the second, then the third, and all three simmer together. But chopping onions is different. That's working: the cook's hands are full, and nothing else can happen. Async helps with waiting. It doesn't help with working.
The ordinary way
import time
def fetch(page):
time.sleep(0.2)
return f"{page} page"
start = time.perf_counter()
for page in ["home", "about", "contact"]:
print(fetch(page))
print(f"{time.perf_counter() - start:.1f} seconds")
home page
about page
contact page
0.6 seconds
time.sleep(0.2) stands in for a network call, which spends most of its time just waiting. Three waits, one after another, 0.6 seconds (timings vary a little, so we round to one decimal). Nearly all of it went on doing nothing.
async def gives you a coroutine
import asyncio
async def greet():
return "hello"
print(type(greet))
coro = greet()
print(type(coro))
print(asyncio.run(coro))
<class 'function'>
<class 'coroutine'>
hello
With async in front of def, greet is still a function. But calling it runs nothing inside. You get back a coroutine object, like a pot that's ready but isn't on the stove yet. asyncio.run starts the event loop (our cook), runs the coroutine to the end and gives back the value.
await: pause me, let others run
import asyncio
async def fetch(page):
await asyncio.sleep(0.2)
return f"{page} page"
async def main():
result = await fetch("home")
print(result)
asyncio.run(main())
home page
asyncio.run(main()) is the door from ordinary code into async code. When fetch reaches await asyncio.sleep(0.2), the pot goes on the stove: fetch pauses on that line and control goes back to the event loop, which is now free. When the time is up, the loop picks fetch up from the same line, and the return value rides back into result. You can only write await inside an async def.
Mistake one: the forgotten await
import asyncio
async def fetch(page):
await asyncio.sleep(0.2)
return f"{page} page"
async def main():
print(fetch("home"))
asyncio.run(main())
<coroutine object fetch at 0x0000016B04951F20>
S04L05_2_Async/forgot_await.py:10: RuntimeWarning: coroutine 'fetch' was never awaited
print(fetch("home"))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Calling fetch only made a coroutine object, so that's what print shows (the address changes every run). fetch never ran. There's a warning but no traceback, and the program finishes normally, so this one is easy to miss. When you see a coroutine object where you expected a value, look for the missing await.
Three awaits in a row are not faster
import asyncio
import time
async def fetch(page):
await asyncio.sleep(0.2)
return f"{page} page"
async def main():
start = time.perf_counter()
print(await fetch("home"))
print(await fetch("about"))
print(await fetch("contact"))
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())
home page
about page
contact page
0.6 seconds
Each await waits for its own answer before the next line runs, so there was only ever one pot on the stove. Async doesn't speed anything up on its own. You have to start things together.
asyncio.gather: all the pots at once
import asyncio
import time
async def fetch(page):
await asyncio.sleep(0.2)
return f"{page} page"
async def main():
start = time.perf_counter()
pages = await asyncio.gather(
fetch("home"), fetch("about"), fetch("contact")
)
print(pages)
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())
['home page', 'about page', 'contact page']
0.2 seconds
gather turns each coroutine into a task on the event loop's list. home starts, hits its sleep and hands control back; then about does the same, then contact. All three wait at the same time. The results come back as one list, in the order you asked for them. Nothing here ran at the same instant; they just waited together.
Watching the turns
import asyncio
async def worker(name, pause):
print(name, "start")
for step in (1, 2):
await asyncio.sleep(pause)
print(name, "step", step)
async def main():
await asyncio.gather(
worker("A", 0.1),
worker("B", 0.15),
worker("C", 0.25),
)
asyncio.run(main())
A start
B start
C start
A step 1
B step 1
A step 2
C step 1
B step 2
C step 2
Each worker prints "start", reaches its await and hands over, so all three start straight away. Then they wake in order of their timers: A at 0.1, B at 0.15, A again at 0.2, and slow C at 0.25. Only one worker runs at any moment, and they swap only at an await. Nobody gets interrupted halfway through a line.
TaskGroup: the other way to start tasks together
import asyncio
import time
async def fetch(page):
await asyncio.sleep(0.2)
return f"{page} page"
async def main():
start = time.perf_counter()
async with asyncio.TaskGroup() as group:
home = group.create_task(fetch("home"))
about = group.create_task(fetch("about"))
print(home.result())
print(about.result())
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())
home page
about page
0.2 seconds
async with works like the with you know from context managers. create_task puts a coroutine on the list and hands you a task object. At the end of the block, main waits until every task has finished, so there's no await on those lines. The big difference from gather: if one task in the group fails, the group cancels the others, so nothing is left running by accident.
Async generators
import asyncio
async def stream(text):
for word in text.split():
await asyncio.sleep(0.05)
yield word
async def main():
async for word in stream("one word at a time"):
print(word)
asyncio.run(main())
one
word
at
a
time
Put yield inside an async def and you have an async generator; read it with async for. Each word comes out after its own small wait, and during every wait the event loop is free. This is the shape behind an AI tool's answer appearing word by word; see LLM streaming.
Mistake two: blocking the loop
import asyncio
import time
async def worker(name):
print(name, "start")
time.sleep(0.2)
print(name, "done")
async def main():
start = time.perf_counter()
await asyncio.gather(
worker("A"), worker("B"), worker("C")
)
print(f"{time.perf_counter() - start:.1f} seconds")
asyncio.run(main())
A start
A done
B start
B done
C start
C done
0.6 seconds
This looks right: async def, gather, three workers. But time.sleep knows nothing about the event loop and has no await, so it never hands control back. A starts and the whole loop stops with it. All the async words, none of the benefit. One ordinary blocking call freezes every task on the loop, so inside async code always do your waiting with await.
Heavy work has the same effect. In the lesson's cpu_work.py, two tasks each add up five million numbers under gather, and the output is "A start, A done, B start, B done". There's no await inside, so A keeps the cook busy until it's finished. That's the chopping onions. For heavy work, Python has threads and processes instead, which are a separate topic.
Waiting or working?
| Task | Kind | Async helps? |
|---|---|---|
| Getting a web page, querying a database, calling an AI model | waiting | yes |
| Adding up huge numbers, resizing thousands of photos | working | no |
| A program that only ever does one thing at a time | either | ordinary code is fine |
You'll see async def in web frameworks like FastAPI, because one server spends its day waiting on many requests at once. It's the same idea.
Quick recap
async defgives you a coroutine;asyncio.runstarts it;awaitpauses it so others can run.gatherandTaskGroupstart several together, so their waits overlap.- Watch for a forgotten
await(a coroutine object and a "never awaited" warning) and fortime.sleepon the loop.
Try it yourself
Fetch three pretend pages with gather, print each one and how long it took. You should see about 0.2 seconds, not 0.6.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
