LearnPy Hub
AdvancedAdvancedLesson 24 of 32

Async Basics

Watch the ideaWaiting without blocking
async def task(name, secs):
    print(name, "start")
    await asyncio.sleep(secs)
    print(name, "done")

async def main():
    await asyncio.gather(task("A", 2), task("B", 1))
A
start
B
A start

Task A starts, then reaches await asyncio.sleep(2).

1Level 1 · BasicsBasics

Some programs spend most of their time waiting: for a web page to download, a database to answer, a file to arrive. Async programming lets one program do other useful work during those waits, instead of sitting idle. Python's tools for this are async, await and the asyncio module.

An everyday picture

Making breakfast: you put the kettle on, and while it boils you make toast. You don't stand staring at the kettle. One cook (one program) handles several tasks by switching to another task whenever the current one has to wait.

Coroutines: async def and await

import asyncio

async def boil_water():
    print("kettle on")
    await asyncio.sleep(2)    # wait without blocking
    print("water ready")
  • async def defines a coroutine, a function that can pause.
  • await pauses this coroutine until the awaited thing finishes, letting other coroutines run meanwhile.
  • asyncio.sleep() is the async version of waiting. (time.sleep() would freeze everything.)

Running it

A program starts its async part with asyncio.run(main()), usually as the last line. Calling a coroutine without awaiting it does nothing; it just creates a coroutine object.

Doing things at the same time: gather

await asyncio.gather(a(), b(), c()) runs several coroutines concurrently and returns their results as a list, in the order you listed them. Three 1-second waits take about 1 second in total instead of 3.

Tasks

asyncio.create_task(coro()) starts a coroutine in the background straight away, and you await the task later to get its result. asyncio.wait_for(coro(), timeout=2) gives up if something takes too long.

When to use async

Async helps with lots of waiting (network calls, web servers, chat bots). It does not speed up heavy calculations, because those keep the processor busy rather than waiting.

Key points: async def makes a coroutine; await pauses it while others run; asyncio.run(main()) starts everything; gather runs coroutines concurrently; async is for waiting, not for heavy computation.

See it in actionHow an event loop takes turns

This is a plain-Python model of an event loop: each task runs until it pauses, then goes to the back of the queue so the next task can run.

Step-by-step

Try it yourselfExample 1: Your first coroutine

The program pauses for half a second at each await. In this editor, put asyncio.run(main()) on the last line.

example_1.py
Output appears here
Fill in the blanks

Your first coroutine

Fill the blanks so the coroutine waits briefly and then prints done.

blanks.py
import asyncio

 def main():
     asyncio.sleep(0.01)
    print("done")

asyncio.run(main())
Fix the bug

Forgot to await

This should print Result: 42, but it prints something strange instead. Fix it.

buggy.py

Example 2: One after another vs together

Run the three tasks in sequence, then together with gather, and compare the times.

example_2.py
Output appears here
Fill in the blanks

Run them together

Fill the blank so both tasks run at the same time and the program prints [1, 2].

blanks.py
import asyncio

async def job(n):
    await asyncio.sleep(0.01)
    return n

async def main():
    results = await asyncio.(job(1), job(2))
    print(results)

asyncio.run(main())

Example 3: Order of events

Each worker prints when it starts and when it finishes. Shorter waits finish first.

example_3.py
Output appears here
Your turn

Who finishes first?

Write async def say(word, delay) that sleeps for delay seconds and then prints the word. Run say("slow", 0.05) and say("fast", 0.01) together with gather, so the output is fast then slow.

my_code.py

Example 4: Tasks and timeouts

create_task starts work in the background; wait_for gives up after a time limit.

example_4.py
Output appears here
Your turn

Add up the downloads

Each fetch(n) pretends to download n files. Gather fetch(3), fetch(5) and fetch(2) together and print the total: 10.

my_code.py

2Level 2 · IntermediateLimits, timeouts and collecting results

as_completed

asyncio.as_completed(tasks) gives results in the order they finish, not the order they started, so you can show the fastest answers first.

Limiting concurrency

Starting 1000 downloads at once can overload a server. asyncio.Semaphore(5) lets only 5 run at the same time; the rest wait their turn.

Timeouts and errors

asyncio.wait_for(job, timeout=1) cancels a slow job. gather(..., return_exceptions=True) collects errors as values instead of stopping everything at the first one.

Example 5: Results as they finish

The 0.1-second job arrives first even though it was started last.

example_5.py
Output appears here

Example 6: A semaphore, a timeout and gathered errors

At most 2 downloads run at once; one fails and one times out, but the others still finish.

example_6.py
Output appears here

3Level 3 · AdvancedQueues, producers and consumers

asyncio.Queue

A queue connects tasks safely: producers await q.put(item), consumers await q.get(). A bounded queue (maxsize=3) makes fast producers wait, which is called back-pressure.

Cancellation

task.cancel() raises CancelledError inside the task at its next await. Clean up in finally. asyncio.TaskGroup (3.11+) starts tasks together and cancels the rest if one fails.

Don't block the loop

A plain time.sleep() or a long calculation freezes every task. Use await asyncio.sleep(), and move heavy CPU work out with asyncio.to_thread or a process pool.

Example 7: A canteen queue with two cooks

The counter takes orders faster than the cooks finish; the bounded queue makes it wait.

example_7.py
Output appears here

Example 8: Cancelling and a TaskGroup

The watcher is cancelled and cleans up in finally; the TaskGroup waits for all its tasks.

example_8.py
Output appears here
Common mistakeCalling time.sleep() inside a coroutine freezes every task, not just the current one. Inside async code, use await asyncio.sleep(). Also, forgetting await before a coroutine call means it never actually runs.
Exercise · predict the output

What does this print?

import asyncio

async def square(n):
    await asyncio.sleep(0.01)
    return n * n

async def main():
    print(await asyncio.gather(square(2), square(3)))

asyncio.run(main())
Quick quiz · 5 questions
1. What does async def create?
2. What does await do?
3. Three coroutines each wait 1 second. Roughly how long does asyncio.gather on all three take?
4. Which is the right way to wait inside a coroutine?
5. Async programming mostly helps with...
Ready to practice async basics?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Async Basics · LearnPy Hub