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:
>>> 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")
... 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.
Related Resources
Tutorial
Async Programming in Python: From Generators to asyncio
Learn how Python async programming works. Write async functions with async and await, and run slow I/O operations concurrently with asyncio.
For additional information on related topics, take a look at the following resources: