coroutine

In Python, a coroutine is an object representing a computation that can be paused and resumed. Coroutines can be entered, exited, and resumed at many different points. It’s the object you get when you call a coroutine function.

To execute the code in a coroutine, you need to await it or run it in an event loop.

Example

Here’s an example of a coroutine:

Python
>>> import asyncio

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

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

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

In this example, greet() is a coroutine function that uses asyncio.sleep() to simulate a non-blocking task. The main() function calls greet() to create a coroutine object that you can await.

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 Jan. 24, 2025 • Reviewed by Dan Bader