What is a coroutine object?
- A coroutine is a special kind of function that can pause and resume its execution, allowing asynchronous programming.
- When you call an async function, it doesn’t run immediately like a regular function.
- Instead, it returns a coroutine object — essentially a “promise” that it will run when awaited.
Coroutine object in practice
async def say_hello():
print("Hello!")
return "Done"
result = say_hello() # This returns a coroutine object, it does NOT execute yet
print(result) # <coroutine object say_hello at 0x...>
# To actually run the coroutine and get the result, you need to await it:
output = await say_hello() # Now it runs, prints "Hello!" and returns "Done"
print(output) # "Done"
Why does this matter?
- Coroutine objects represent tasks that haven’t run yet.
- You must
await
them inside an async function to actually execute the code and get the result. - If you don’t
await
and just return the coroutine, it’s like returning a “recipe” instead of the “finished dish.”
In your FastAPI app
- Your repository functions are async (return coroutine objects).
- If you return the coroutine itself (without
await
), FastAPI tries to serialize the coroutine object, which causes errors. - You must await those async calls so FastAPI gets the actual data to send in the response.
Summary:
Term | Meaning |
---|---|
coroutine function | A function defined with async def
|
coroutine object | The result of calling a coroutine function — a "lazy" task not yet run |
await |
The keyword that runs the coroutine and gets its result |