How to make an asynchronous function Python
Learn how to create an asynchronous function in Python with an example. See how to use the asyncio library to achieve better performance in your code.
Making an Asynchronous Function in Python
Asynchronous programming is a style of programming that allows for the execution of multiple tasks at the same time. It allows for tasks to be started and completed in a non-sequential order, making it possible to execute tasks in parallel. Python has a range of built-in tools and libraries that make it easy to create asynchronous functions.
The asyncio
module is the standard library used for asynchronous programming in Python. It provides a framework of primitives, such as coroutines
and futures
, that can be used to build asynchronous tasks. To create an asynchronous function, you need to use the async
keyword in front of the function declaration. For example, to create an asynchronous function that prints out a message:
async def say_hello():
print("Hello!")
say_hello()
You can then call the asynchronous function like you would any other function. It will execute asynchronously in the background. To ensure that all tasks are completed in the correct order, you can use the asyncio.wait
function. This function takes a list of coroutines
as an argument and will wait until all tasks have completed before continuing execution. For example, to wait until two asynchronous functions have completed:
async def say_hello_1():
print("Hello 1!")
async def say_hello_2():
print("Hello 2!")
await asyncio.wait([say_hello_1(), say_hello_2()])
The asyncio
module also provides a range of utility functions that can be used to simplify the creation of asynchronous tasks. For example, the asyncio.gather
function can be used to execute a list of tasks in parallel and return the results when all tasks have completed. To execute two asynchronous functions in parallel and return the results:
async def say_hello_1():
return "Hello 1!"
async def say_hello_2():
return "Hello 2!"
results = await asyncio.gather(say_hello_1(), say_hello_2())
print(results)
The output of this code will be a list containing the results of both functions: ['Hello 1!', 'Hello 2!']
. As you can see, Python makes it easy to create asynchronous functions with its built-in tools and libraries.