Python Async/Await
Many programs spend most of their time waiting: for a web server to reply, a database query to finish, a file to download. While one request waits, the program could be starting others. Asynchronous programming with async and await lets a single thread juggle many waiting tasks, switching between them whenever one is paused.
The standard library module for this is asyncio.
Coroutines: async def and await
A function defined with async def is a coroutine function. Calling it doesn't run it — it creates a coroutine object that must be awaited. Inside, await pauses the coroutine until the awaited operation is done, letting other tasks run meanwhile.
import asyncio
async def greet(name):
await asyncio.sleep(0.01) # pretend to wait for something
return f"Hello, {name}"
async def main():
message = await greet("Dao")
print(message)
asyncio.run(main())Hello, Dao
asyncio.run(main()) starts the event loop, runs main() until it finishes, and shuts the loop down. It's the usual entry point of an async program.
Note: In the browser, ExcelTAD runs Python through Pyodide, whose event loop is already running in the page. If a playground here reports "asyncio.run() cannot be called from a running event loop", replace the last line
asyncio.run(main())withawait main()— Pyodide allowsawaitat the top level. In a normal Python script, keepasyncio.run(main()).
Running tasks concurrently with gather
Awaiting coroutines one after another runs them in sequence. asyncio.gather() runs several at once and returns their results in the order you passed them, regardless of which finished first:
import asyncio
async def download(name, seconds):
print(f"start {name}")
await asyncio.sleep(seconds)
print(f"finish {name}")
return f"{name}: {int(seconds * 1000)} ms"
async def main():
results = await asyncio.gather(
download("big.zip", 0.3),
download("small.txt", 0.1),
download("photo.jpg", 0.2),
)
print(results)
asyncio.run(main())start big.zip
start small.txt
start photo.jpg
finish small.txt
finish photo.jpg
finish big.zip
['big.zip: 300 ms', 'small.txt: 100 ms', 'photo.jpg: 200 ms']
All three "downloads" started immediately, and the whole thing took about 0.3 seconds — the longest single wait — instead of 0.6 seconds one after another.
Sync vs async
| Synchronous | Asynchronous | |
|---|---|---|
| Define | def f(): |
async def f(): |
| Call | f() runs it |
await f() inside another coroutine |
| Waiting | time.sleep(1) blocks everything |
await asyncio.sleep(1) lets others run |
| Start program | just call functions | asyncio.run(main()) |
| Good for | CPU work, simple scripts | many network/disk waits at once |
Tip: Async helps with waiting, not with heavy computation. For CPU-bound work (number crunching), use
multiprocessingorconcurrent.futures.ProcessPoolExecutor.
Tasks
asyncio.create_task() schedules a coroutine to start running in the background right away. You can do other work and await the task later:
import asyncio
async def brew_coffee():
print("coffee: brewing")
await asyncio.sleep(0.2)
print("coffee: ready")
return "coffee"
async def toast_bread():
print("toast: toasting")
await asyncio.sleep(0.1)
print("toast: ready")
return "toast"
async def main():
coffee_task = asyncio.create_task(brew_coffee())
toast_task = asyncio.create_task(toast_bread())
print("setting the table while we wait")
breakfast = [await toast_task, await coffee_task]
print("breakfast:", breakfast)
asyncio.run(main())setting the table while we wait
coffee: brewing
toast: toasting
toast: ready
coffee: ready
breakfast: ['toast', 'coffee']
Notice that "setting the table" printed first: creating a task only schedules it. The tasks begin as soon as main reaches its first await.
Timeouts and errors
asyncio.wait_for() cancels an operation that takes too long. Exceptions inside coroutines propagate to whoever awaits them, so normal try/except works:
import asyncio
async def slow_service():
await asyncio.sleep(1)
return "data"
async def broken_service():
await asyncio.sleep(0.01)
raise ConnectionError("service unavailable")
async def main():
try:
await asyncio.wait_for(slow_service(), timeout=0.05)
except asyncio.TimeoutError:
print("slow_service timed out")
try:
await broken_service()
except ConnectionError as err:
print("caught:", err)
results = await asyncio.gather(broken_service(), asyncio.sleep(0.01, result="ok"),
return_exceptions=True)
print([type(r).__name__ if isinstance(r, Exception) else r for r in results])
asyncio.run(main())slow_service timed out
caught: service unavailable
['ConnectionError', 'ok']
With return_exceptions=True, gather returns exceptions as results instead of failing on the first one.
Limiting concurrency
Starting 1,000 requests at once can overwhelm a server. An asyncio.Semaphore allows only a fixed number inside a block at the same time:
import asyncio
active = 0
peak = 0
async def fetch(page, limit):
global active, peak
async with limit: # wait here if 2 fetches are already running
active += 1
peak = max(peak, active)
await asyncio.sleep(0.05)
active -= 1
return f"page {page}"
async def main():
limit = asyncio.Semaphore(2)
pages = await asyncio.gather(*(fetch(p, limit) for p in range(1, 6)))
print(pages)
print("most fetches running at once:", peak)
asyncio.run(main())['page 1', 'page 2', 'page 3', 'page 4', 'page 5']
most fetches running at once: 2
async with is the asynchronous version of a context manager; there's also async for for asynchronous iterators.
Test yourself
What does calling an async def function return?
- Its return value
- A coroutine object that must be awaited
- A thread
- None
Why use await asyncio.sleep(1) instead of time.sleep(1) in async code?
- It's more accurate
- It pauses only the current coroutine, letting others run
- time.sleep doesn't exist
- It sleeps for longer
In what order does asyncio.gather(a(), b(), c()) return results?
- The order they finished
- Random order
- The order they were passed in
- Alphabetical order