How To Run Async Function Python

In this tutorial, you’ll learn how to work with asynchronous functions in Python, which helps to manage simultaneous tasks or activities with more efficiency, particularly when dealing with input-output bound situations like web scraping or API calls.

Using the asyncio library in Python can save time when executing multiple requests at the same time rather than using the synchronous approach.

Before starting, ensure that you are using Python 3.7 or higher, as this tutorial assumes the use of new asyncio features available in these versions.

Step 1: Install and import necessary libraries

To use async functions in Python, you need to have the asyncio library installed. You can install this library using pip:

Next, import the required libraries in your Python script:

Step 2: Create an asynchronous function with async/await

To create an asynchronous function, use the async def keyword for defining the function. Inside the async function, use the await keyword for asynchronous calls that should be executed concurrently. Here’s an example of a simple async function that simulates a delay using asyncio.sleep:

Step 3: Run the async function in an event loop

To run an async function, you need to use an event loop, which is responsible for scheduling and executing asynchronous tasks in a concurrent way. Here’s how to create a simple event loop that runs the async_function created above:

This will execute the async_function() and wait for it to complete.

Step 4: Running multiple async functions concurrently

To run multiple async functions concurrently, use asyncio.gather():

This example will run 5 instances of the async_function() concurrently, and the main() function will complete only after all 5 tasks are finished.

Full code example

In this example, you will see that all 5 instances of the async function start at the same time, and then complete a second later.

Starting async function...
Starting async function...
Starting async function...
Starting async function...
Starting async function...
Async function completed!
Async function completed!
Async function completed!
Async function completed!
Async function completed!

Conclusion

In this tutorial, you’ve learned how to create and run async functions in Python using the asyncio library. This method can improve the efficiency of your code by allowing multiple tasks to run concurrently, improving the overall speed of execution.