Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PY
Python
0/14 completed
Beginner
Hello PythonVariables and typesWorking with stringsConditions and loopsFunctions
Intermediate
Lists, tuples, dicts and setsFiles and exceptionsModules and the standard library
Advanced
Classes and OOPIterators and generatorsDecorators and context managers
Pro
Async PythonTesting and type hintsVirtual environments, packages and real projects
Tracks / Python / Pro

Async Python

Most programs spend a lot of time waiting: for a web API to respond, a database query to finish, a file to download. Asynchronous code lets one program do other useful work during those waits, so 100 slow network requests take about as long as the slowest one, instead of the sum of all of them.

The problem: waiting in line

Python · editable

Three one-second waits, done one after another: 3 seconds. The CPU did nothing while waiting.

The async version

Python · editable

All three start immediately and wait at the same time: about 1 second in total.

The vocabulary

Term Meaning
async def Defines a coroutine function. Calling it returns a coroutine object, without running it yet.
await x Pause this coroutine until x is finished; the event loop runs other coroutines meanwhile.
event loop The scheduler that switches between coroutines whenever one is waiting.
asyncio.run(main()) Starts the event loop and runs main to completion: the entry point of an async program.
asyncio.gather(...) Runs several awaitables concurrently and collects all their results.
task A coroutine scheduled to run in the background: asyncio.create_task(...).

await only works inside async def. Forgetting await is the classic mistake: you get a coroutine object instead of a result:

Python · editable

Tasks: start now, wait later

Python · editable

Results in completion order, and timeouts

Python · editable

Limiting concurrency with a semaphore

Firing 10,000 requests at once will get you rate-limited or banned. A semaphore allows only N at a time:

Python · editable

Producer and consumer with a queue

Python · editable

(:= is the "walrus operator": it assigns and tests in one expression.)

Real async libraries

Async only helps if the slow parts are async too. Use libraries built for it:

python
import asyncio
import httpx                                  # pip install httpx

async def main():
    async with httpx.AsyncClient() as client:
        urls = [f"https://api.github.com/users/{u}" for u in ["torvalds", "gvanrossum"]]
        responses = await asyncio.gather(*(client.get(u) for u in urls))
        for r in responses:
            print(r.json()["name"])

asyncio.run(main())
Need Async library
HTTP requests httpx, aiohttp
Web APIs FastAPI, Starlette
PostgreSQL asyncpg, SQLAlchemy (async mode)
Redis redis.asyncio

Async vs threads vs processes

Tool Best for
asyncio Lots of waiting on the network (thousands of connections)
threads (concurrent.futures.ThreadPoolExecutor) Waiting on blocking libraries that aren't async
processes (multiprocessing, ProcessPoolExecutor) Heavy CPU work (number crunching) across several cores

Async does not make CPU-heavy code faster: while a coroutine computes, nothing else runs. And never call a blocking function like time.sleep() or requests.get() inside a coroutine, because it freezes the whole event loop.

Practice

  1. Write async def countdown(name, n) that prints name: n every 0.1 s down to 1, and run two countdowns concurrently with gather.
  2. Simulate fetching 5 URLs with random delays (random.uniform(0.1, 0.5)), print them as they finish with as_completed, and the total time.
  3. Add a timeout of 0.3 s to each fetch and count how many timed out.
Python · editable
✎ Check your understanding

1.What does calling an async def function return?

2.Three async calls each wait 1 second. Run with asyncio.gather, about how long does it take?

3.Which is the best fit for speeding up heavy CPU-bound number crunching?

← Decorators and context managers