Skip to content

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, added to the language in Python 3.5 (PEP 492) via the async and await syntax, which became reserved keywords in Python 3.7. The asyncio library provides a built-in event loop for running coroutines, though other frameworks like Trio and AnyIO also support them.

Example

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

Language: 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.

Async IO in Python: A Complete Walkthrough

Tutorial

Python's asyncio: A Hands-On Walkthrough

Explore how Python asyncio works and when to use it. Follow hands-on examples to build efficient programs with coroutines and awaitable tasks.

advanced python

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

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 28, 2026 • Reviewed by Dan Bader