Academic Block

Asynchronous PythonGet Certified

What Is Asynchronous Programming?

Many programs spend most of their time waiting: for a web server to answer, for a file to load, or for a database to return its rows. In a normal program, the whole program stands still during every wait, and the computer does nothing useful. Asynchronous programming lets a program switch to other work while one task waits, so many waiting tasks can overlap in time. Python supports this style with the asyncio module and the async and await keywords, and it is the foundation of fast web servers, chat bots, and programs that talk to many services at once.

  • Coroutines: functions defined with async def that can pause and resume.
  • await: pauses a coroutine until the awaited operation is done, and lets other work run meanwhile.
  • The event loop: the scheduler that runs coroutines and switches between them. asyncio.run() starts it.
  • Concurrency tools: gather() and create_task() run several coroutines at the same time.
  • Timeouts and errors: wait_for() limits a wait, and return_exceptions=True collects failures.
  • Queues, async generators, and async context managers: tools for sharing work and managing resources.

Coroutines: async def and await

A coroutine is a special function that you create by writing async def instead of def. Inside it, the keyword await marks the places where the function may pause and let the program do something else, for example while it waits for a network answer. Here, asyncio.sleep() stands in for any slow operation, because it waits without blocking the rest of the program. The function asyncio.run() starts the event loop, runs one top-level coroutine until it finishes, and then closes the loop.

Try It: Your First Coroutine

Click Test My Code. Change "Olivia" to your own name and run it again.

What this code does: It defines a coroutine that waits for half a second and then returns a greeting. A second coroutine called main() awaits the first one and prints the greeting. The call to asyncio.run() starts everything.
import asyncio

async def greet(name):
    await asyncio.sleep(0.5)
    return f"Hello, {name}!"

async def main():
    message = await greet("Olivia")
    print(message)

asyncio.run(main())

Coroutine Objects and Sequential Awaits

Calling a coroutine function does not run its body. Instead, it returns a coroutine object, which is a paused piece of work that waits for someone to await it or to give it to the event loop. This surprises many students, because a normal function call runs immediately. If you await several coroutines one after another, each one finishes before the next one starts, so the waits add up. That is correct and sometimes needed, but it does not make the program faster, and the next sections show how to overlap the waits.

Try It: Weather Checks, One After Another

Click Test My Code. Look at the type that is printed on line 9, and then add a third city to the end of main().

What this code does: It defines a coroutine that simulates a weather lookup. It creates a coroutine object without running it, prints its type, and then awaits it. A second lookup is awaited directly, so the two lookups run one after the other.
import asyncio

async def fetch_temperature(city, degrees):
    await asyncio.sleep(0.1)
    return f"{city}: {degrees} degrees"

async def main():
    coro = fetch_temperature("Denver", 54)
    print(type(coro).__name__)
    print(await coro)
    print(await fetch_temperature("Miami", 82))

asyncio.run(main())

Running Coroutines Together with asyncio.gather

The real power of asyncio appears when several coroutines wait at the same time. The function asyncio.gather() takes several coroutines, starts them all, and returns their results in a list when the last one has finished. Because the waits overlap, the total time is about the time of the longest task and not the sum of all tasks. The results come back in the same order in which you passed the coroutines, even if a later one finished first, which makes the output easy to predict.

Try It: A Kitchen with Three Orders

Click Test My Code. Change the three waiting times and check whether the answer on the last line still says True.

What this code does: It prepares three dishes that need 0.3, 0.2, and 0.1 seconds. gather() runs them at the same time. The program prints the results and checks that the total time was shorter than the 0.6 seconds that three sequential waits would need.
import asyncio
import time

async def prepare(dish, seconds):
    await asyncio.sleep(seconds)
    return f"{dish} is ready"

async def main():
    start = time.perf_counter()
    results = await asyncio.gather(
        prepare("Burger", 0.3),
        prepare("Fries", 0.2),
        prepare("Shake", 0.1),
    )
    elapsed = time.perf_counter() - start
    print(results)
    print("Faster than doing them one by one:", elapsed < 0.55)

asyncio.run(main())

Background Work with asyncio.create_task

The function asyncio.create_task() wraps a coroutine in a task and schedules it to run on the event loop. Unlike a plain await, creating a task does not pause your code, so you can start several jobs, do something else, and collect the results later. A task begins to run as soon as the current coroutine reaches an await and gives the event loop a chance to switch. Keep a reference to every task that you create, so that you can await it later and read its result.

  • asyncio.create_task(coro) schedules the coroutine and returns a task at once.
  • Awaiting a task gives you its return value, or raises the exception that it raised.
  • task.done() tells whether the task has finished, and task.cancel() asks it to stop.
  • A task only gets time to run when the code around it awaits something.

Try It: Two Downloads at Once

Click Test My Code. Read the order of the messages carefully: the text Tasks created appears before either download starts.

What this code does: It creates two download tasks, a slow one and a fast one, and prints a message before awaiting them. The event loop starts both downloads when main() pauses, and the fast download finishes first, even though it was created second.
import asyncio

async def download(file_name, seconds):
    print(f"Start {file_name}")
    await asyncio.sleep(seconds)
    print(f"Finished {file_name}")
    return file_name.upper()

async def main():
    slow = asyncio.create_task(download("report.pdf", 0.4))
    fast = asyncio.create_task(download("photo.png", 0.1))
    print("Tasks created")
    print(await slow, await fast)

asyncio.run(main())

Setting a Time Limit with asyncio.wait_for

Anything that depends on a network or a remote service can take much longer than expected, or never finish at all. A good program does not wait forever, and asyncio.wait_for() lets you set a time limit on any awaitable. If the limit runs out, the awaited coroutine is cancelled and a TimeoutError is raised in your code, where you can catch it with an ordinary try and except block. This keeps your program responsive and gives you a chance to show a friendly message or to try again.

Try It: A Lookup That Takes Too Long

Click Test My Code. Change timeout=0.3 to timeout=3 and see the answer arrive.

What this code does: It defines a lookup that needs two seconds and awaits it with a time limit of 0.3 seconds. The limit expires first, so the lookup is cancelled, the exception is caught, and the program continues normally.
import asyncio

async def slow_lookup():
    await asyncio.sleep(2)
    return "Found it"

async def main():
    try:
        answer = await asyncio.wait_for(slow_lookup(), timeout=0.3)
        print(answer)
    except asyncio.TimeoutError:
        print("Lookup timed out")
    print("Program continues")

asyncio.run(main())

Handling Errors in Concurrent Tasks

When several coroutines run together, one of them may fail while the others succeed. By default, gather() raises the first exception that it sees, and you lose the results of the tasks that worked. If you pass return_exceptions=True, the exceptions are returned in the result list instead of being raised, so you can go through the list and treat each outcome on its own. This is a good choice when the jobs are independent, for example when you check the stock of many items and one lookup fails.

Try It: A Stock Check with One Bad Item

Click Test My Code. Change -3 to 3 and notice that the problem line disappears.

What this code does: It checks the stock of three items at the same time. The coroutine raises a ValueError for a negative count. Because return_exceptions=True is set, gather() returns the exception as a result, and the loop prints either a stock line or a problem message for each item.
import asyncio

async def check_stock(item, count):
    await asyncio.sleep(0.1)
    if count < 0:
        raise ValueError(f"{item} has a bad count")
    return f"{item}: {count} in stock"

async def main():
    results = await asyncio.gather(
        check_stock("Jeans", 14),
        check_stock("Boots", -3),
        check_stock("Hats", 6),
        return_exceptions=True,
    )
    for result in results:
        if isinstance(result, Exception):
            print("Problem:", result)
        else:
            print(result)

asyncio.run(main())

Sharing Work with asyncio.Queue

Real programs often have one part that creates work and another part that processes it, such as a website that receives orders and a kitchen that cooks them. An asyncio.Queue connects the two safely: a producer puts items into the queue, and a consumer takes them out. When the queue is empty, await queue.get() pauses the consumer until a new item arrives, without wasting any computer time. A special marker value such as None is a simple way to tell the consumer that no more work is coming.

  • await queue.put(item) adds an item, and it waits if a size limit has been reached.
  • await queue.get() removes the oldest item, and it waits while the queue is empty.
  • A None marker is a common signal for “no more work”.
  • Several consumers can share one queue to split the work between them.

Try It: A Breakfast Kitchen

Click Test My Code. Add a fourth dish to the list and watch it travel through the queue.

What this code does: A producer places three breakfast orders into a queue, one every tenth of a second. A consumer takes each order out and cooks it. When the producer is finished, it sends a None marker, and the consumer stops. gather() runs both of them at the same time.
import asyncio

async def producer(queue):
    for order in ["Pancakes", "Omelet", "Waffles"]:
        await queue.put(order)
        print(f"Order placed: {order}")
        await asyncio.sleep(0.1)
    await queue.put(None)

async def consumer(queue):
    while True:
        order = await queue.get()
        if order is None:
            break
        print(f"Cooking: {order}")

async def main():
    queue = asyncio.Queue()
    await asyncio.gather(producer(queue), consumer(queue))
    print("Kitchen closed")

asyncio.run(main())

Async Generators and Async Context Managers

The ideas of generators and context managers also exist in an asynchronous form. An async generator is a function with async def that uses yield, and you loop over it with async for, so that every item may need an await before it is produced. An async context manager is used with async with, and its setup and cleanup steps may await as well, for example when a database connection is opened and closed. The decorator @asynccontextmanager from contextlib builds one from a generator, in the same way as @contextmanager does for normal code.

Try It: A Diner Menu

Click Test My Code. Notice that the closing message is printed after the last special, even though no line of code calls it.

What this code does: It defines an async context manager that opens and closes a diner, and an async generator that serves three daily specials with a short wait before each one. The program enters the context manager with async with and loops over the specials with async for.
import asyncio
from contextlib import asynccontextmanager

@asynccontextmanager
async def open_diner():
    print("Diner open")
    try:
        yield "Open until 10 PM"
    finally:
        print("Diner closed")

async def daily_specials():
    for dish in ["Meatloaf", "Clam chowder", "Apple pie"]:
        await asyncio.sleep(0.1)
        yield dish

async def main():
    async with open_diner() as hours:
        print(hours)
        async for dish in daily_specials():
            print("Special:", dish)

asyncio.run(main())
Tip: Use asyncio for programs that wait a lot, such as network requests, and not for heavy calculations. Never call a blocking function such as time.sleep() inside a coroutine, because it freezes the whole event loop. Use await asyncio.sleep() instead, and keep a reference to every task that you create.

Using Async Code with User Input

Asynchronous code is often used in programs that react to a user, such as a travel app that looks up several cities at once or a delivery app that gives up on a slow order. Remember that input() is a blocking function, so the examples below read the input before the event loop starts, and then hand the values to the coroutines. This is a clean pattern: collect and convert the input first, and let the asynchronous part do the waiting. Convert numbers with float() or int() before you use them, because input() always returns text.

Try It: A Multi-City Forecast

The Program Input box is already filled with Denver, Miami, Boston. Click Run Code straight away, then try Seattle, Chicago and see the message for a city without data.

What this code does: It reads a comma-separated list of cities and looks up all of them at the same time with gather(). A dictionary holds the forecasts, and the coroutine returns a line for each city, or a message when the city is not in the dictionary.
import asyncio

FORECASTS = {"denver": 61, "miami": 84, "boston": 47, "seattle": 55}

async def get_forecast(city):
    await asyncio.sleep(0.2)
    degrees = FORECASTS.get(city.lower())
    if degrees is None:
        return f"{city}: no data"
    return f"{city}: {degrees} degrees"

text = input("Cities (comma separated): ")
cities = [name.strip() for name in text.split(",")]

async def main():
    results = await asyncio.gather(*(get_forecast(city) for city in cities))
    for line in results:
        print(line)

asyncio.run(main())

Try It: How Long Will You Wait for Pizza?

The Program Input box is filled with 0.2. Click Run Code, then try 1, which is longer than the delivery takes.

What this code does: It asks how many seconds the customer is willing to wait. A coroutine simulates a pizza delivery that takes half a second, and wait_for() uses the typed number as its time limit. The program prints either the delivery message or a message that the customer gave up.
import asyncio

async def order_pizza():
    await asyncio.sleep(0.5)
    return "Pizza delivered to Brooklyn"

patience = float(input("Seconds you will wait: "))

async def main():
    try:
        message = await asyncio.wait_for(order_pizza(), timeout=patience)
        print(message)
    except asyncio.TimeoutError:
        print(f"Gave up after {patience} seconds")

asyncio.run(main())

Common Mistakes with Asynchronous Python

Asynchronous code looks very similar to normal code, and this similarity hides several traps for new students. Most mistakes either stop the program from running concurrently, or leave a coroutine that never runs at all. The list below covers the problems that appear most often, and it is worth a quick read whenever an async program feels slow, prints a warning about a coroutine that was never awaited, or freezes without any error message.

  • Forgetting await: calling greet("Olivia") without await only creates a coroutine object, and Python warns that it was never awaited.
  • Using time.sleep() in a coroutine: it blocks the whole event loop. Use await asyncio.sleep().
  • Awaiting one task after another: separate await lines run in sequence. Use gather() or create_task() to overlap the waits.
  • Calling asyncio.run() inside a running loop: it raises an error in environments such as notebooks that already run a loop. Use await main() there.
  • Expecting async code to speed up calculations: it helps with waiting, not with heavy computing. Use multiprocessing for CPU-bound work.
  • Losing the reference to a task: a task that nobody holds can be garbage collected before it finishes. Store it in a variable or a list.
  • Ignoring exceptions in tasks: an error in a task that is never awaited can go unnoticed. Await the task, or use return_exceptions=True.
  • Waiting forever: network operations can hang. Protect them with asyncio.wait_for().

Key Takeaways

Asynchronous programming lets one Python program keep many waiting jobs in progress at the same time, and it is the basis of fast web servers, scrapers, and chat applications. It takes a little practice to think in coroutines and tasks, but the rules are few and consistent. The points below summarize this lesson, and they prepare you for the next lesson on algorithms and complexity, where you will learn to measure and compare how fast different solutions are. Remember them whenever your program spends its time waiting.

  • A function defined with async def is a coroutine, and calling it returns a coroutine object that does not run until it is awaited.
  • The keyword await pauses the current coroutine until the awaited operation finishes, and lets other work run.
  • asyncio.run() starts the event loop and runs one top-level coroutine to the end.
  • asyncio.gather() runs several coroutines concurrently and returns their results in order, and return_exceptions=True keeps failures from stopping the rest.
  • asyncio.create_task() starts work in the background, and the task runs when the current coroutine awaits.
  • asyncio.wait_for() sets a time limit and raises TimeoutError when the limit is exceeded.
  • asyncio.Queue, async for, and async with connect producers, consumers, and resources. Never block the event loop with time.sleep().

Frequently Asked Questions

These are the questions that students ask most often when they learn about asynchronous programming in Python. The answers are brief and practical, and each idea appears in one of the examples above. If something is still unclear, try writing a tiny program with two coroutines that print a message before and after a short sleep, and run them first with two separate awaits and then with gather() to see the difference.

What is asynchronous programming in Python?

Asynchronous programming is a style in which a program switches to other work while one task is waiting, for example for a network response. Python supports it with the asyncio module and the async and await keywords. It lets one program handle many waiting tasks at the same time without using many threads.

What do async and await mean in Python?

The keyword async before def creates a coroutine function, which can pause and resume. The keyword await, used inside a coroutine, pauses it until the awaited operation is finished and lets the event loop run other tasks in the meantime. You can only use await inside an async function.

What is the difference between asyncio and threading?

With asyncio, one thread runs many coroutines and each coroutine decides where to pause by using await, so switches happen only at known points. With threading, the operating system switches between threads at any moment. Asyncio is lighter for many waiting tasks, while threads can also be used with code that blocks.

What does asyncio.run do?

The function asyncio.run creates a new event loop, runs the coroutine that you give it until it finishes, and then closes the loop. It is normally called once, at the bottom of a program, with your main coroutine. It cannot be called when an event loop is already running in the same thread.

What is asyncio.gather used for?

The function asyncio.gather starts several coroutines at the same time and returns a list of their results in the order in which you passed them. Because the waits overlap, the total time is close to the longest single task. With return_exceptions=True, failures are returned in the list instead of being raised.

Why should I use asyncio.sleep instead of time.sleep?

The function time.sleep blocks the whole thread, so the event loop cannot run any other coroutine while it waits. The function asyncio.sleep, used with await, pauses only the current coroutine and lets the others continue. Inside async code, always use await asyncio.sleep.

How do I set a timeout for an async operation?

Wrap the awaitable in asyncio.wait_for and give a timeout in seconds, for example await asyncio.wait_for(task(), timeout=3). If the time runs out, the awaitable is cancelled and a TimeoutError is raised, which you can catch with try and except.

When should I use asynchronous code?

Use it when your program spends most of its time waiting, for example for web requests, database queries, or files, and when many such tasks can overlap. It does not make heavy calculations faster, so for CPU-bound work use multiprocessing or a faster algorithm instead.

Ready for the next step?Learn how to measure and compare the speed of different solutions.
Next: Algorithms & Complexity →