How to Get Return Value From Asyncio Coroutine
You can get return values from coroutines and tasks in asyncio by awaiting them directly.
In this tutorial, you will discover how to get return values in asyncio.
Let's get started.
Asyncio Return Values
Python asyncio allows us to run program tasks in coroutines.
We may need to return values from coroutines to the caller.
Further, we may wrap our coroutines in asyncio.Task objects and needs to retrieve return values from the wrapped coroutine.
Finally, we may execute many coroutines concurrently using asyncio.gather() and need to retrieve the return values from each coroutine.
We can explore how to retrieve return values from asyncio coroutines.
Return Value from Asyncio Coroutine
We can retrieve a return value from a coroutine by awaiting it.
It assumes that the other coroutine being awaited returns a value.
For example:
# coroutine that returns a value
async def other_coro():
return 100
Awaiting the other coroutine will suspend the calling coroutine and schedule the other coroutine for execution. Once the other coroutine has been completed, the calling coroutine will resume. The return value will be passed from the other coroutine to the caller.
For example:
...
# execute coroutine and retrieve return value
value = await other_coro()
Return Value from Asyncio Task
A coroutine can be wrapped in an asyncio.Task object.
This is helpful for independently executing the coroutine without having the current coroutine await it.
This can be achieved using the asyncio.create_task() function.
For example:
...
# wrap coroutine in a task and schedule it for execution
task = asyncio.create_task(other_coro())
You can learn more about how to create tasks in the tutorial:
There are two ways to retrieve the return value from an asyncio.Task, they are:
- Await the task.
- Call the result() method.
We can await the task to retrieve the return value.
If the task is scheduled or running, then the caller will suspend until the task is complete and the return value will be provided.
If the task is completed, the return value will be provided immediately.
For example:
...
# get the return value from a task
value = await task
Unlike a coroutine, we can await a task more than once without raising an error.
For example:
...
# get the return value from a task
value = await task
# get the return value from a task
value = await task
We can also get the return value from the task by calling the result() method on the asyncio.Task object.
For example:
...
# get the return value from a task
value = task.result()
This requires that the task is done. If not, an InvalidStateError exception will be raised.
If the task was canceled a CancelledError exception will be raised.
You can learn more about getting the result from tasks in the tutorial:
Return Values from asyncio.gather()
The asyncio.gather() function takes one or more coroutines, executes the provided coroutines, and will suspend until all provided coroutines are done.
We can retrieve the return values from coroutines executed via asyncio.gather().
The asyncio.gather() function returns an iterable of return values for the provided coroutines that can be accessed directly.
For example:
...
# execute coroutines and get return values
values = await asyncio.gather(other_coro1(), other_coro2())
You can learn more about how to use the asyncio.gather() function in the tutorial:
Now that we know how to get return values in asyncio, let's look at some worked examples.
Example of Asyncio Coroutine Return Value
We can explore how to get a return value from a coroutine in asyncio.
In this example, we will call a coroutine from the main coroutine and retrieve its return value.
The complete example is listed below.
# SuperFastPython.com
# example of return value from coroutine
import asyncio
# custom coroutine
async def task():
# return a value
return 'hello from coroutine'
# main coroutine
async def main():
# create the coroutine
coro = task()
# execute the coroutine and get the return value
value = await coro
# report the return value
print(value)
# run the asyncio program
asyncio.run(main())
Running the example first creates the main() coroutine and then executes it as the entry point into the asyncio program.
The main() coroutine runs and creates the task() coroutine. It then suspends and schedules the task() coroutine for execution.
The task() coroutine runs and returns a string value.
The main() coroutine resumes and receives the string return value from the task() coroutine.
The return value is then reported.
This highlights how we can return values from coroutines in an asyncio program.
hello from coroutine
Next, let's look at how to return a value from a task.
Example of Asyncio Task Return Value
We can explore how to get a return value from an asyncio.Task in asyncio.
There are two ways to get the return value from a task, let's look at both.
Await Task
We can await a task to get the return value.
In this example, we will schedule a coroutine as an independent task.
We will then await the task in order to retrieve its return value.
The complete example is listed below.
# SuperFastPython.com
# example of return value from a task
import asyncio
# custom coroutine
async def task_coro():
# return a value
return 'hello from coroutine'
# main coroutine
async def main():
# create the coroutine
coro = task_coro()
# create and execute the task
task = asyncio.create_task(coro)
# wait for the task to complete and get the return value
value = await task
# report the return value
print(value)
# run the asyncio program
asyncio.run(main())
Running the example first creates the main() coroutine and then executes it as the entry point into the asyncio program.
The main() coroutine runs and creates the task_coro() coroutine. This coroutine is then wrapped in an asyncio.Task and scheduled for execution.
The main() coroutine then awaits the task.
The task_coro() coroutine runs and returns a string value.
The main() coroutine resumes and receives the return value from the coroutine, passed along automatically by the asyncio.Task object that wraps it.
The return value is then reported.
This highlights how we can retrieve a return value from a coroutine wrapped in a task by awaiting the task.
hello from coroutine
Next, we will retrieve the return value from the task via the result() method.
Get Task Result
We can call the result() method on the task to get the return value.
In this example, we will schedule a coroutine as an independent task.
We will then await the task in order for it to complete, then call the result() method on the task to retrieve the return value.
The complete example is listed below.
# SuperFastPython.com
# example of return value from a task
import asyncio
# custom coroutine
async def task_coro():
# return a value
return 'hello from coroutine'
# main coroutine
async def main():
# create the coroutine
coro = task_coro()
# create and execute the task
task = asyncio.create_task(coro)
# wait for the task to complete
await task
# get the return value
value = task.result()
# report the return value
print(value)
# run the asyncio program
asyncio.run(main())
Running the example first creates the main() coroutine and then executes it as the entry point into the asyncio program.
The main() coroutine runs and creates the task_coro() coroutine. This coroutine is then wrapped in an asyncio.Task and scheduled for execution.
The main() coroutine then waits for the task to complete.
The task_coro() coroutine runs and returns a string value.
The main() coroutine resumes. It then calls the result() method on the task to retrieve the return value.
The return value is then reported.
This highlights how we can retrieve a return value from a coroutine wrapped in a task via the result() method on the task object.
hello from coroutine
Next, we will look at how to retrieve return values from coroutines executed via the gather() function.
Example of Asyncio gather() Return Values
We can explore how to get return values from coroutines executed using asyncio.gather().
In this example, we will create a list of coroutine objects. We will then unpack the list and provide it to the asyncio.gather() function to execute.
This will return a list of return values once all coroutines are done, which we will report directly.
The complete example is listed below.
# SuperFastPython.com
# example of return value from a task
import asyncio
# custom coroutine
async def task_coro():
# return a value
return 'hello from coroutine'
# main coroutine
async def main():
# create multiple coroutines
coros = [task_coro(), task_coro(), task_coro()]
# execute all coroutines concurrently
values = await asyncio.gather(*coros)
# report return values
print(values)
# run the asyncio program
asyncio.run(main())
Running the example first creates the main() coroutine and then executes it as the entry point into the asyncio program.
The main() coroutine runs and creates a list of coroutine objects.
The list of coroutine objects is then unpacked using the star operator (*) and provided to the asyncio.gather() to be executed.
The main() coroutine then awaits the gather() coroutine function.
The gather() coroutine executes, in turn running all three provided coroutines concurrently. Each coroutine returns a value. The gather() coroutine returns an iterable of these return values.
The main() coroutine resumes and receives the iterable of return values from the gather() function.
The return values are then reported directly.
['hello from coroutine', 'hello from coroutine', 'hello from coroutine']
Takeaways
You now know how to get return values in asyncio.
If you enjoyed this tutorial, you will love my book: Python Asyncio Jump-Start. It covers everything you need to master the topic with hands-on examples and clear explanations.