Stop 14 · Advanced PythonTopics · 6/8

asyncio & async/await

Part of the Python Roadmap

In short

A chat server or scraper may need to juggle thousands of slow network calls. asyncio does it in one thread by switching to other work whenever a task is waiting, which is how FastAPI and many modern libraries stay fast.

asyncio runs many I/O tasks concurrently in a single thread using an event loop. async def defines coroutines, await pauses them while waiting, and asyncio.gather runs several at once.

The jaadu runs a busy roadside chai stall, stirring one steaming pot, pouring from another and taking a coin from a smiling customer all at once.

Think of it like this

One chaiwala, many customers

A skilled chaiwala puts milk on one stove, tea on another, takes the next order while both boil and never stands staring at a pot. He is one person, but nobody waits longer than needed. The event loop is the chaiwala, and await is the moment he says "this one's boiling, let me serve someone else".

Watch it happen

Three price checks on one event loop

Event loop
Shop A (2s)
Shop B (1s)

start fetch, hits await

1/4Task A sends its request and pauses at await. The loop is free immediately.

The big ideas

What you need to know

async def makes a coroutine

Calling it doesn't run it. It returns a coroutine object that runs when awaited or scheduled on the loop.

await pauses politely

await hands control back to the event loop until the result is ready, so other tasks can run.

gather and TaskGroup

asyncio.gather(a(), b()) runs coroutines together. Python 3.11+ also has asyncio.TaskGroup, which cancels the rest if one fails.

Never block the loop

time.sleep or requests.get freeze every task. Use asyncio.sleep, httpx.AsyncClient or aiohttp instead.

See it in code

Walk through the code

python
1import asyncio2import time3 4async def fetch_price(shop: str, delay: float) -> str:5    print(f"asking {shop}...")6    await asyncio.sleep(delay)          # stands in for a real network call7    return f"{shop} replied after {delay}s"8 9async def main() -> None:10    start = time.perf_counter()11    results = await asyncio.gather(12        fetch_price("Flipkart", 2),13        fetch_price("Amazon", 1),14        fetch_price("Croma", 1.5),15    )16    for line in results:17        print(line)18    print(f"total: {time.perf_counter() - start:.1f}s")   # about 2.0s, not 4.5s19 20asyncio.run(main())

1/4A coroutine. At await, it pauses and lets the event loop run other tasks.

Three simulated network calls run concurrently on one thread. Replace asyncio.sleep with httpx.AsyncClient().get(url) for real requests.

Save yourself the pain

Common mistakes

Oops

Calling fetch_price("Amazon", 1) without await.

Do this instead

That only creates a coroutine object and Python warns it was never awaited. Write await fetch_price(...) or pass it to gather.

Oops

Using time.sleep() or requests.get() inside async def.

Do this instead

Blocking calls freeze the whole loop. Use await asyncio.sleep() and an async HTTP client like httpx.

Oops

Expecting asyncio to speed up heavy calculations.

Do this instead

It only helps while tasks wait. For CPU work, use processes, or loop.run_in_executor with a ProcessPoolExecutor.

Your mission

Async weather check

~30 min

Quick check

What happens when a coroutine reaches await asyncio.sleep(2)?

Go deeper

  1. 1Write two coroutines with asyncio.sleep and run them with asyncio.gather.
  2. 2Fetch several URLs concurrently with httpx.AsyncClient.
  3. 3Avoid calling blocking functions like time.sleep inside async code.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge