Python Coroutines and async/await
Understand coroutine functions, coroutine objects, and await, and learn how Python suspends and resumes coroutine execution.
Intermediate
A coroutine is Python’s language-level way to describe work that can suspend and resume. You define a coroutine function with async def, call it to create a coroutine object, and use await inside a coroutine to suspend it until another awaitable produces a result.
async def creates a coroutine function
A function defined with
async def is a coroutine function even when its body contains no
await. Calling the function creates a coroutine object; it does not execute the body to completion by itself.
Output
Ready to run.
A coroutine object needs to be driven
The object returned by a coroutine function is awaitable. A top-level program commonly uses
asyncio.run() to run an entry-point coroutine and obtain its result. Calling the coroutine function and then forgetting to await or otherwise run the resulting object does not execute its body.
Output
Ready to run.
await suspends a coroutine
An
await expression suspends the current coroutine until the awaited object produces its result. Control can then continue with the value of that result.
Output
Ready to run.
Awaiting composes coroutines
One coroutine can await another and then use the returned value. This gives asynchronous code a direct way to build larger operations from smaller coroutine functions.
Output
Ready to run.
Coroutine exceptions propagate through await
An exception raised while a coroutine is running can propagate to the coroutine that awaits it. Ordinary
try and
except handling still applies.
Output
Ready to run.
async def does not require await
An
async def function remains a coroutine function even when it never suspends. It can still be awaited and can still be used as an asynchronous entry point.
Output
Ready to run.
yield from is not for coroutine functions
Coroutine functions use
await to wait for awaitables. A
yield from expression is not permitted inside a coroutine function.
Output
Ready to run.
Quick check
Quick check
What normally happens when a coroutine function is called?
result = (main) # main is async def main(): ...
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.