Coroutine
In one line
A coroutine is a function defined with 'async def' that can pause at 'await' and resume later.
In simple words
A coroutine is a function that can be paused (at await) and resumed later. Unlike a regular function that runs start-to-finish, a coroutine can yield control back to the event loop multiple times.
Coroutines are created by async def. Calling a coroutine function returns a coroutine object — it doesn't run until you await it or schedule it with asyncio.run() or asyncio.gather().
Coroutines are the building blocks of async/await. They're lightweight (no thread per coroutine), so you can have thousands running concurrently in one event loop.
Example
import asyncio
async def countdown(name, n):
while n > 0:
print(f"{name}: {n}")
await asyncio.sleep(1) # Pause here
n -= 1
return f"{name} done"
# coro is a coroutine object, not running yet
coro = countdown("A", 3)
print(type(coro)) # <class 'coroutine'>
result = asyncio.run(coro)
print(result)Calling an async function returns a coroutine object. It only executes when awaited or run by the event loop.
Common confusions
Confused with: generator
The difference: Generators use 'yield' to produce values and are pulled by the caller. Coroutines use 'await' to consume values/operations and are driven by an event loop. Generators produce data; coroutines consume time/operations.
Related terms
Related Resources
Related Lessons
- Python Async
Coroutines.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.