Last Updated on November 2, 2022
You can run an asyncio coroutine via the run() function, by awaiting it within another coroutine, or by scheduling it as Task.
In this tutorial, you will discover how to run a coroutine with asyncio in Python.
Let’s get started.
Need to Run An Asyncio Coroutine
The asyncio module provides coroutine-based concurrency in Python.
It is specifically designed for Asynchronous I/O, also called non-blocking IO and focuses on non-blocking socket programming.
asyncio is often a perfect fit for IO-bound and high-level structured network code.
— asyncio – Asynchronous I/O
This is achieved through the async/await syntax in Python.
Coroutines are defined using the “async” keyword, and running coroutines can execute and wait on coroutines using the “await” keyword.
Coroutines are central to asyncio.
As such, how can we run a new coroutine?
Run loops using all CPUs, download your FREE book to learn how.
How to Run an Asyncio Coroutine
There are three key ways to run an asyncio coroutine, they are:
- Call asyncio.run()
- Await the Coroutine
- Schedule as a Task
Let’s take a closer look at each approach in turn.
Call asyncio.run()
A coroutine can be executed by creating an instance of the coroutine and passing it to the asyncio.run() function.
For example:
1 2 3 4 5 |
... # create the coroutine coro = custom_coroutine() # start the event loop and execute the coroutine asyncio.run(coro) |
This approach to executing a coroutine is typically performed in a single line.
For example:
1 2 3 |
... # start the event loop and execute the coroutine asyncio.run( custom_coroutine()) |
This will start the asyncio runtime, called the event loop, and execute the coroutine.
It is the primary way that asyncio applications are started.
Await the Coroutine
Another way to run a coroutine is to await it from a running coroutine.
For example:
1 2 3 4 5 6 7 |
# defines a custom coroutine def another_coroutine(): ... # create the coroutine coro = custom_coroutine() # execute and wait for the coroutine to finish await coro |
This is typically performed in a single line.
For example:
1 2 3 |
... # execute and wait for the coroutine to finish await custom_coroutine() |
Recall that the “await” keyword takes an awaitable.
If we use the await keyword and pass it a new coroutine, it will pause the current coroutine, execute the new coroutine and wait for the new coroutine to complete before resuming.
Schedule as a Task
A coroutine can be wrapped in a Task and executed independently.
This will schedule the coroutine for execution at some future time.
This can be achieved by calling the asyncio.create_task() function from within a coroutine.
For example:
1 2 3 4 5 |
... # create the coroutine coro = custom_coroutine() # wrap in a task and schedule for execution task = asyncio.create_task(coro) |
This is typically performed in a single line.
For example:
1 2 3 |
... # wrap in a task and schedule for execution task = asyncio.create_task(custom_coroutine()) |
The task will not execute until the event loop has an opportunity to execute the task.
This may be when the current coroutine finishes.
We can also explicitly pause the current coroutine and wait for the task to complete via the await keyword.
This is because a Task is an awaitable, e.g. an object that can be waited on via the await keyword.
For example:
1 2 3 4 5 |
... # wrap in a task and schedule for execution task = asyncio.create_task(custom_coroutine()) # wait for the task to complete await task |
Now that we know three ways to execute a coroutine, let’s look at some worked examples.
Example of Calling asyncio.run()
A coroutine can be executed by starting the asyncio event loop and passing the coroutine for execution.
This can be achieved by calling the asyncio.run() function and passing it the coroutine instance.
The example below defines a custom coroutine that takes a message and prints it. The coroutine is then created and passed to the asyncio.run() function for execution.
1 2 3 4 5 6 7 8 9 10 11 |
# SuperFastPython.com # example of executing a coroutine using the event loop import asyncio # custom coroutine async def custom_coro(message): # report the message print(message) # create and execute coroutine asyncio.run(custom_coro('Hi from a coroutine')) |
Running the example creates the coroutine and passed it a message to report.
The coroutine is passed to the asyncio.run() function that starts the asyncio event loop and executes the coroutine.
The message is then reported from the coroutine and the asyncio event loop is shut down.
This highlights how we can run a coroutine directly using the asyncio event loop.
1 |
Hi from a coroutine |
Free Python Asyncio Course
Download your FREE Asyncio PDF cheat sheet and get BONUS access to my free 7-day crash course on the Asyncio API.
Discover how to use the Python asyncio module including how to define, create, and run new coroutines and how to use non-blocking I/O.
Example of Running a Coroutine by Awaiting
A coroutine can be executed by awaiting it from within another running coroutine.
This can be achieved by creating the new coroutine and using the await keyword.
The example below creates a coroutine and passes it to the asyncio.run() function as in the example above to start the asyncio event loop. The custom coroutine then creates its own second coroutine and awaits it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# SuperFastPython.com # example of executing a coroutine from a coroutine import asyncio # another custom coroutine async def new_coro(message): # report the message print(message) # custom coroutine async def custom_coro(message): # execute the new coroutine await new_coro('Hi from coroutine within a coroutine') # report the message print(message) # create and execute coroutine asyncio.run(custom_coro('Hi from a coroutine')) |
Running the example first creates the custom coroutine with a custom message and starts the asyncio event loop.
The coroutine executes and creates a second coroutine with a different message and awaits it.
This pauses the first coroutine, allowing the second coroutine to execute.
The second coroutine executes, reports its own message then terminates. The first coroutine then continues on and reports its message.
This highlights how we can run a coroutine by calling it from within a coroutine.
1 2 |
Hi from coroutine within a coroutine Hi from a coroutine |
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
Example of Running a Coroutine as a Task
We can run a coroutine by wrapping it in a task via the asyncio.create_task() function.
This will schedule the coroutine for independent execution and provide a handle on the coroutine.
The example below creates and runs a custom coroutine as per normal. The custom coroutine then creates a second coroutine and then wraps the coroutine in a task. This schedules the coroutine for independent execution. The custom coroutine then waits for the task to be done.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# SuperFastPython.com # example of executing a coroutine as a task from a coroutine import asyncio # another custom coroutine async def new_coro(message): # report the message print(message) # custom coroutine async def custom_coro(message): # create the new coroutine coro = new_coro('Hi from coroutine within a coroutine') # wrap the coroutine in a task and schedule for execution task = asyncio.create_task(coro) # wait for the task to complete await task # report the message print(message) # create and execute coroutine asyncio.run(custom_coro('Hi from a coroutine')) |
Running the example first creates the custom coroutine with a message and starts the asyncio event loop.
The custom coroutine then creates a second coroutine with another message. It then wraps the coroutine in a task that immediately schedules it for execution.
The custom coroutine then explicitly waits for the task to complete, although this is not required.
The second coroutine executes via the task and reports its message, then is done.
The first coroutine then continues on and reports its message.
1 2 |
Hi from coroutine within a coroutine Hi from a coroutine |
Further Reading
This section provides additional resources that you may find helpful.
Python Asyncio Books
- Python Asyncio Mastery, Jason Brownlee (my book!)
- Python Asyncio Jump-Start, Jason Brownlee.
- Python Asyncio Interview Questions, Jason Brownlee.
- Asyncio Module API Cheat Sheet
I also recommend the following books:
- Python Concurrency with asyncio, Matthew Fowler, 2022.
- Using Asyncio in Python, Caleb Hattingh, 2020.
- asyncio Recipes, Mohamed Mustapha Tahrioui, 2019.
Guides
APIs
- asyncio — Asynchronous I/O
- Asyncio Coroutines and Tasks
- Asyncio Streams
- Asyncio Subprocesses
- Asyncio Queues
- Asyncio Synchronization Primitives
References
Takeaways
You now know how to run a coroutine using asyncio in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Florian Schneider on Unsplash
Do you have any questions?