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 defthat 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()andcreate_task()run several coroutines at the same time. - Timeouts and errors:
wait_for()limits a wait, andreturn_exceptions=Truecollects 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.
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())asyncio module is part of the standard library and contains the event loop and the tools for asynchronous code.async before def turns greet() into a coroutine function.await asyncio.sleep(0.5) pauses this coroutine for half a second. While it waits, the event loop is free to run other work.main() coroutine that starts all the other work.await runs greet("Olivia") and waits for its result, which is stored in message.Hello, Olivia!.asyncio.run() creates the event loop, runs main() until it is finished, and closes the loop.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().
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())sleep() and run().main(). It is only for readability.fetch_temperature() does not run its body. It only creates a coroutine object that is waiting to be awaited.coroutine.Denver: 54 degrees.Miami: 82 degrees.asyncio.run() runs main() to the end.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.
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())sleep(), gather(), and run().time module provides perf_counter(), a precise clock for measuring durations.main(). It is only for readability.gather() receives several coroutines, runs them concurrently, and await waits until all of them have finished.gather() at this point.['Burger is ready', 'Fries is ready', 'Shake is ready'].Faster than doing them one by one: True.asyncio.run() runs main() to the end.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, andtask.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.
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())create_task(), sleep(), and run().Start report.pdf followed by Start photo.png.Finished photo.png appears first, and Finished report.pdf follows after 0.4 seconds.main(). It is only for readability.create_task() schedules the report download and returns a task at once. Nothing has run yet, because main() has not paused.Tasks created.await pauses main(), so the event loop starts both downloads. When both are finished, the output is REPORT.PDF PHOTO.PNG.asyncio.run() runs main() to the end.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.
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())wait_for(), TimeoutError, and the other tools.main(). It is only for readability.wait_for() allows the lookup only 0.3 seconds. When the time is over, it cancels the lookup and raises TimeoutError.TimeoutError that wait_for() raised.Lookup timed out.Program continues.asyncio.run() runs main() to the end.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.
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())sleep(), gather(), and run().ValueError with a clear message.main(). It is only for readability.gather() runs all three checks at the same time.ValueError.return_exceptions=True, an exception becomes an ordinary item in the result list and does not stop the others.results, in the order of the calls.Problem: Boots has a bad count.Jeans: 14 in stock and Hats: 6 in stock.asyncio.run() runs main() to the end.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
Nonemarker 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.
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())Queue, sleep(), gather(), and run().await queue.put() adds the order to the queue. The queue has no size limit, so this does not wait.Order placed: Pancakes.None into the queue as a signal that the work is finished.await queue.get() returns the oldest item. If the queue is empty, the consumer pauses here until an item arrives.None means that no more orders are coming.break statement ends the loop, and the consumer finishes.Cooking: Pancakes.main(). It is only for readability.asyncio.Queue() creates an empty queue with no size limit.gather() waits until both have finished. The messages alternate: placed, cooking, placed, cooking, placed, cooking.Kitchen closed.asyncio.run() runs main() to the end.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.
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())sleep() and run().asynccontextmanager builds an async context manager from an async generator function.async def and contains one yield.yield runs when the async with block starts. The output is Diner open.try block guarantees that the finally part runs.yield gives the opening hours to the name after as and pauses until the block ends.Diner closed.async def and yield is an async generator.main(). It is only for readability.async with runs the setup, and the value that was yielded is stored in hours.Open until 10 PM.async for asks the generator for one dish at a time and awaits each one.Special: Meatloaf, Special: Clam chowder, and Special: Apple pie. When the block ends, the cleanup prints Diner closed.asyncio.run() runs main() to the end.Tip: Useasynciofor programs that wait a lot, such as network requests, and not for heavy calculations. Never call a blocking function such astime.sleep()inside a coroutine, because it freezes the whole event loop. Useawait 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.
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())sleep(), gather(), and run().get() returns the temperature, or None when the city is unknown. lower() makes the search independent of capital letters.None means that the dictionary has no data for the city.no data.Denver: 61 degrees.Denver, Miami, Boston, is stored as text. The input is read before the event loop starts.strip() removes the spaces around each name. The result is a list of three names.main(). It is only for readability.* passes them to gather() as separate arguments. All the waits overlap.Denver: 61 degrees, Miami: 84 degrees, and Boston: 47 degrees.asyncio.run() runs main() to the end.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.
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())wait_for(), sleep(), and run().0.2 is converted from text to the float 0.2.main(). It is only for readability.0.2, the limit is shorter than the delivery time of 0.5 seconds.1, the output is Pizza delivered to Brooklyn.TimeoutError.0.2, the output is Gave up after 0.2 seconds.asyncio.run() runs main() to the end.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: callinggreet("Olivia")withoutawaitonly creates a coroutine object, and Python warns that it was never awaited. - Using
time.sleep()in a coroutine: it blocks the whole event loop. Useawait asyncio.sleep(). - Awaiting one task after another: separate
awaitlines run in sequence. Usegather()orcreate_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. Useawait 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 defis a coroutine, and calling it returns a coroutine object that does not run until it is awaited. - The keyword
awaitpauses 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, andreturn_exceptions=Truekeeps 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 raisesTimeoutErrorwhen the limit is exceeded.asyncio.Queue,async for, andasync withconnect producers, consumers, and resources. Never block the event loop withtime.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.