asyncio - How to use Async/Await in Python.

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
In this article, we will discuss how we can use async/await in Python.
If you're familiar with JavaScript, you'll notice that we use async, which causes a function to return a promise, and await, which causes a function to wait for a promise.
When we need to fetch some data from the servers, we use async and await to delay the function's execution until the promise is resolved, and in the meantime, the other functions are executed without blocking the other tasks.
This happens because the code is executed asynchronously.
Well, this is not the JavaScript tutorial so we don't dive deep into the working of asynchronous operations in JavaScript.
But we'll learn the meaning of Asynchronous ahead in this article.
Just above we encountered the term Asynchronous. What does it mean?
For simple understanding, it just means that not occurring at the same time. It is theoretical meaning. We gonna learn the Practical definition of asynchronous ahead of this article with an example that lets you understand it easily.

asyncio - Asynchronous IO :We cannot use async/await syntax directly in the function to make it asynchronous rather we can use a Python package asyncio to achieve the goal.
Before diving into the asyncio module let's understand Asynchronous IO first.
note: I refer to asynchronous IO as async IO and
asynciois a Python package.
async IO is designed to work on concurrent programming that has received support in Python, from Python 3.4 through Python 3.7 and beyond this.
Let's understand it with the help of an example:
We will understand it by the example of a chess master Judit Polgár.
Judit Polgár, a chess master hosts a chess exhibition in which some amateur players took part and she plays with them. She has two ways of conducting the exhibition: synchronously and asynchronously.
Here are the assumptions:
There are 24 opponents.
Judit makes each chess move in 5 seconds.
Opponents each take 55 seconds to make a move.
Games average 30 pair moves (60 moves total).
Synchronous approach:
Judit only plays one game at a time and never moves on until the current game is finished. Each game lasts (55 + 5) 30 = 1800 seconds or 30 minutes. The duration of the exhibition is 24*30 = 720 minutes or 12 hours.
Asynchronous approach:
Judit moves from table to table in this method, making one move at each table. She leaves the table after each move and waits for the opponent to make their next move.
Judit Polgár takes 24*5 = 120 seconds or 2 minutes to complete one move on all 24 games. As a result, the entire exhibition has been reduced to 120*30 = 3600 seconds or just 1 hour.
From the above example, it concludes that async IO tasks that take a long waiting period get blocked and allow other tasks to run during that downtime.
The Source of this example.
Let's move to the next part of this article.
asyncio module :According to documentation, asyncio is a type of library that helps us to write concurrent code using async/await syntax.
Since it's a module we have to import it.
import asyncio
asyncio works with Coroutines. Coroutines are nothing but a specialized version of Python generator functions.
A coroutine is a function that can suspend its execution before reaching the return and it can indirectly pass the control to another coroutine for some time.
Coroutines declared with the async/await syntax is the preferred way of writing asyncio applications.
Here's the simple use case:
import asyncio
async def func():
print("Hey....")
await asyncio.sleep(1)
print("I am here...")
asyncio.run(func())
async def func() - We used async to make the function asynchronous.
await asyncio.sleep(1) - Here, we used await and used the asyncio.sleep() to delay the execution of the print statement below it.
asyncio.run(func()) - Finally, we are calling the function. You can see that we used asyncio to call the function, if we try to call the function simply as usual then we get a RuntimeError.
Until here, you surely get some idea of Asynchronous IO and asyncio use cases.
Let's look at the examples demonstrating the Asynchronous function:
Asynchronous
import asyncio
async def write():
print("Hey")
await asyncio.sleep(1)
print("there")
async def main():
await asyncio.gather(write(), write(), write())
if __name__ == "__main__":
import time
start = time.perf_counter()
asyncio.run(main())
elapsed = time.perf_counter() - start
print(f"File executed in {elapsed:0.2f} seconds")
We created two async functions -
First is the write() function that prints Hey then wait for 1 second and then again prints there.
Second is main() function that executeswrite() function 3 times using asyncio.gather().
And then we wrote a code that calculates the time taken to execute the async functions.
Here's the output:

We can clearly see that the whole code was executed in just 1 second using the asynchronous approach.
What if we execute the same code in a Synchronous way:
Synchronous
import time
def write():
print("Hey")
time.sleep(1)
print("there")
def main():
for _ in range(3):
write()
if __name__ == "__main__":
start = time.perf_counter()
main()
elapsed = time.perf_counter() - start
print(f"File executed in {elapsed:0.2f} seconds")
Here's the output:

Here, this code snippet took 3 seconds to execute using the synchronous approach.
Now we are clearly able to see the differences in both approaches and even understand how it's happened.
We can use async/await in Python to make the high-level structured code network for better efficiency.
asyncio is used as a foundation for various Python asynchronous frameworks that provide high-performance networks and web servers, database connection libraries, distributed task queues, etc.
🏆Other articles you might be interested in if you liked this one
✅Performing pattern matching using match-case statements in Python.
✅How to use super() function in Python classes?
✅Different types of inheritances in Python classes.
✅How to implement __getitem__, __setitem__ and __delitem__ in Python classes?
✅How to change the string representation of the objects in Python?
✅What is the difference between sort() and sorted() function in Python?
✅Public, Protected, and Private access modifiers in Python.
That's all for now
Keep coding✌✌