Sub topic 3
Writing coroutines with async def and await
This chapter assumes you are comfortable with Python functions, classes, and context managers. It also assumes you know how exceptions and generators work, and that you can tell I/O-bound work from CPU-bound work. The previous chapter described how the event loop schedules work. This chapter covers how you write the code the loop runs: coroutines.
What `async def` creates
A function defined with async def is a coroutine function. Calling it does not run its body. It returns a coroutine object, which is a paused computation that has not started yet.
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay)
return f"Hello, {name}"
coro = greet("Ada", 0.1)
print(type(coro))
print(asyncio.iscoroutine(coro))
coro.close() # discard it cleanly so Python does not warnThe program prints <class 'coroutine'> and True. Nothing slept, because the body never ran. The coroutine object only does work when something drives it: an await expression, a task, or asyncio.run.
This is the most common source of confusion for newcomers. A plain call such as greet("Ada", 0.1) is not a call in the sense you are used to. It builds a recipe, and something else has to execute it.
What `await` does
await can appear only inside an async def body. It takes an awaitable and does two things:
- It runs that awaitable until it finishes, and the
awaitexpression evaluates to its result. - If the awaitable has to wait (for a timer, a socket, or another task), it suspends the current coroutine and hands control back to the event loop. The loop can then run other ready work.
The suspension is the point of the whole system. Between two await expressions, your coroutine runs without interruption. The loop only regains control at an await that actually has to wait. This is cooperative scheduling: a coroutine yields control by choice, and the loop never preempts it.
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay)
return f"Hello, {name}"
async def main():
message = await greet("Ada", 0.1)
print(message)
asyncio.run(main())Here main awaits greet. While greet waits on asyncio.sleep, the loop is free to run anything else that is ready. In this program nothing else is, so the loop simply waits for the timer. The program prints Hello, Ada.
What you can await
Three kinds of objects are awaitable:
| Awaitable | How you get it | Notes |
|---|---|---|
| Coroutine | Calling an `async def` function | Starts running when awaited. Can be awaited once. |
| Task | `asyncio.create_task(coro)` | Already scheduled. Covered in a later chapter. |
| Future | Low-level APIs, such as `loop.create_future()` | Represents a result that arrives later. You rarely create these directly. |
Anything with an __await__ method counts as awaitable. In everyday application code you will mostly await coroutines and tasks.
Awaiting a coroutine directly does not make anything concurrent. It behaves like a normal function call that may pause in the middle. Two sequential awaits take the sum of their times:
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1)
return n * 2
async def main():
start = time.perf_counter()
a = await fetch(1)
b = await fetch(2)
print(a, b, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())This prints 2 4 2.0s. The second fetch does not begin until the first returns. Concurrency comes from tasks, gather, and TaskGroup, which later chapters cover. A coroutine on its own only gives you the ability to pause.
Return values and exceptions
A coroutine returns values and raises exceptions exactly like a normal function. The caller sees them at the await:
import asyncio
async def parse(text):
await asyncio.sleep(0)
return int(text)
async def main():
try:
value = await parse("not a number")
except ValueError as exc:
print("failed:", exc)
asyncio.run(main())The ValueError raised inside parse propagates out of await parse(...), so an ordinary try/except works. asyncio.sleep(0) is a useful idiom here. It yields to the loop once without waiting for any real time.
Forgotten awaits
The most common coroutine bug is calling a coroutine function and forgetting to await the result.
import asyncio
async def save(record):
await asyncio.sleep(0.1)
print("saved", record)
async def main():
save("a") # bug: the coroutine is created and thrown away
await save("b") # correct
asyncio.run(main())Only saved b is printed. Python also emits a RuntimeWarning: coroutine 'save' was never awaited when the discarded object is garbage collected. Treat that warning as a real bug. The work you intended never happened.
A related bug is using the result without awaiting it:
import asyncio
async def get_count():
await asyncio.sleep(0)
return 3
async def main():
total = get_count() + 1 # TypeError: unsupported operand type(s)
asyncio.run(main())Here get_count() is a coroutine object, not an int. The fix is total = await get_count() + 1. Static checkers such as mypy and pyright catch both bugs, because they know the return type of a coroutine function is Coroutine[..., int] and not int.
Coroutines versus generators
Coroutines grew out of generators, and the connection explains some of their behavior. A generator pauses at yield and the caller resumes it with next(). A coroutine pauses at await and the event loop resumes it. In both cases the function's local variables survive the pause, and the function continues from the exact point where it stopped.
The difference lies in who resumes the function and why. A generator resumes whenever its consumer asks for the next value. A coroutine resumes when the thing it awaited is ready. This is why you cannot loop over a coroutine with for, and why you cannot await a plain generator.
Do not use the older @asyncio.coroutine decorator or yield from for new code. The decorator was removed in Python 3.11, and async def with await replaced both.
Rules and edge cases
awaitoutside anasync defis aSyntaxError. The top level of a normal script is synchronous. You enter the async world withasyncio.run, which the next chapter covers.- A synchronous function cannot await. If a regular
defneeds a result from a coroutine, it must start an event loop, or you must make the functionasync defas well. This "colouring" effect is why async code tends to spread upward through the call stack. - A coroutine can be awaited once. Awaiting the same coroutine object a second time raises
RuntimeError: cannot reuse already awaited coroutine. Call the function again to get a fresh coroutine. - An
async deffunction with noawaitin it is legal. It is still a coroutine function, and it never yields control to the loop. It runs start to finish in one uninterrupted step. - Awaiting something that is already finished does not necessarily suspend. For example,
await asyncio.sleep(0)yields once, butawaiton a completed future returns immediately. Do not rely on anawaitas a guaranteed point where other tasks run. - Calling blocking code, such as
time.sleep(1), inside a coroutine does not suspend it. It freezes the whole loop for that second. Useawait asyncio.sleep(1)instead, and see the later chapter on keeping blocking calls off the loop.
import asyncio
async def once():
return 1
async def main():
coro = once()
print(await coro)
try:
await coro
except RuntimeError as exc:
print(exc)
asyncio.run(main())This prints 1 and then cannot reuse already awaited coroutine.
Decision rules for writing coroutine code
Make a function async def when it awaits something inside it. Leave it as a plain def when it does only fast, CPU-light work such as formatting a string. An unnecessary async def forces every caller to await it and adds overhead with no benefit.
When you write an await, ask what the coroutine is waiting for. If the answer is "a timer, a socket, a database reply, or another task", it belongs in a coroutine. If the answer is "a long computation", await will not help, because the computation still blocks the loop.
Exercise
The following program prints nothing about the result and emits a RuntimeWarning. Explain why, and fix it. import asyncio async def compute(): await asyncio.sleep(0.1) return 42 async def main(): result = compute() print(result) asyncio.run(main())
Show answer
Calling compute() only creates a coroutine object. The body never runs, and print shows the coroutine object, not 42. Python warns that the coroutine was never awaited. The fix is result = await compute(), so the coroutine runs and the await expression evaluates to 42.
Exercise
Two sequential awaits of fetch(1) and fetch(2), each sleeping one second, take about two seconds. Does wrapping them in two separate async def helpers change that? Why or why not?
Show answer
No. Awaiting a coroutine runs it to completion before the next line executes, no matter how many layers of async def are involved. The total stays about two seconds. Concurrency requires scheduling the coroutines as tasks, or using gather or TaskGroup, so that the loop can run both while each one waits.