Sub topic 3
Writing coroutines with async def and await
This chapter assumes you know Python functions, exceptions, and generators, and that you can tell I/O-bound work from CPU-bound work. It also assumes you know the event loop is what switches between pieces of work. Here you will learn how to write those pieces.
What a coroutine is
A coroutine function is a function defined with async def. Calling it does not run its body. It returns a coroutine object, which is a paused computation that something else must drive.
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay)
return f"Hello, {name}"
coro = greet("Ada", 0.1)
print(type(coro))
coro.close()This prints <class 'coroutine'>. The body of greet never ran. The close() call discards the object so Python does not warn that it was never awaited.
What await does
await can only appear inside an async def. It does two things:
- It runs the awaitable on its right until that awaitable finishes.
- While the awaitable is waiting, for example on a timer or a socket, it hands control back to the event loop so other work can run.
The expression's value is whatever the awaited coroutine returns. If the coroutine raises, the exception appears at the await line, so ordinary try/except works.
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())This prints Hello, Ada. asyncio.run(main()) starts the event loop and runs main to completion. The next chapter covers it in detail.
Awaiting is not the same as concurrency
Awaiting a coroutine directly runs it to completion before the next line. Two awaits in a row run one after the other.
import asyncio
import time
async def pause():
await asyncio.sleep(1)
async def main():
start = time.perf_counter()
await pause()
await pause()
print(f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())This prints about 2.0s. Other tasks could run during each pause, but these two calls do not overlap with each other. Running them together needs tasks, which a later chapter covers.
Awaitables
You can await any awaitable. The three common kinds are coroutine objects, tasks, and futures. Anything else raises TypeError.
import asyncio
async def main():
try:
await 5
except TypeError as e:
print(e)
asyncio.run(main())The message says that an int can't be used in an await expression.
The most common mistake: a forgotten await
If you call a coroutine function without await, you get the coroutine object and nothing runs.
import asyncio
async def save():
print("saved")
async def main():
save() # bug: creates a coroutine, never runs it
await save() # correct
asyncio.run(main())Python prints saved once and warns RuntimeWarning: coroutine 'save' was never awaited. Treat that warning as a bug report.
Summary of the rules
| Syntax | Meaning |
|---|---|
| `async def f():` | Defines a coroutine function. Calling it returns a coroutine object. |
| `await x` | Runs `x` and pauses the current coroutine while `x` waits. |
| `return` in a coroutine | Becomes the value of the `await` expression. |
| `await` outside `async def` | A `SyntaxError`. |
Exercise
What does this program print, and how long does it take? async def f(): await asyncio.sleep(0.5); return 1 and async def main(): a = await f(); b = await f(); print(a + b), started with asyncio.run(main()).
Show answer
It prints 2 after about 1 second. Each await f() runs to completion before the next line starts, so the two half-second sleeps happen one after the other and do not overlap.
Exercise
A teammate writes result = fetch_data() inside an async def, where fetch_data is also an async def. Then result is used as if it were data. What is wrong, and what is the fix?
Show answer
Without await, result is a coroutine object and the body of fetch_data never ran. Python also warns that the coroutine was never awaited. The fix is result = await fetch_data().