coroutine function

In Python, a coroutine function is a function that you define with the async def syntax. These functions return coroutine objects that can pause their execution and yield control back to the event loop, allowing other tasks to run.

Coroutine functions are useful when writing asynchronous programs that perform non-blocking input/output (I/O) operations, such as web requests or database queries.

Coroutines are part of Python’s asynchronous programming capabilities, introduced with the asyncio library. This library provides a powerful framework to write asynchronous code using the async and await keywords.

Example

Here’s an example of how to define and use a coroutine function:

Python
>>> import asyncio

>>> async def greet(name):
...     print(f"Hello, {name}!")
...     await asyncio.sleep(1)
...     print(f"How are you?")
...

>>> async def main():
...     await greet("Pythonista")
...

>>> asyncio.run(main())
Hello, Pythonista!
How are you?

In this example, greet() is a coroutine function. You call it from another coroutine, main(), using the await keyword. The asyncio.run() function executes the main() coroutine, starting the event loop.

Tutorial

Getting Started With Async Features in Python

This step-by-step tutorial gives you the tools you need to start making asynchronous programming techniques a part of your repertoire. You'll learn how to use Python async features to take advantage of IO processes and free up your CPU.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 11, 2025 • Reviewed by Leodanis Pozo Ramos