Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Coroutines and async/await

Understand coroutine functions, coroutine objects, and await, and learn how Python suspends and resumes coroutine execution.

Levels: Intermediate ~25 min read

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

Ready to run.

Quick check

Quick check

What normally happens when a coroutine function is called?

result = (main)  # main is async def main(): ...
Was this page helpful?

Mark this learning resource complete to track your learning progress.