
Posted on • Originally published atgeekpython.in
Async/Await: Asynchronous Programming In Python
In this article, we gonna discusshow we can use async/await in Python?
Now, if you are familiar with JavaScript then you might know that we useasync
which makes a function return a promise, andawait
which makes a function wait for a promise.
We useasync
andawait
when we need to fetch some data from the servers to make the execution of the function delay until the promise is resolved and in meantime, the other functions get executed without blocking the other tasks.
This happens because the code is executedasynchronously.
Well, this is not the JavaScript tutorial so we don't dive deep into the working ofasynchronous
operations in JavaScript.
But I do explain the complete meaning ofAsynchronous ahead in this article.
Introduction
Now we gonna discusshow we exactly use async/await in Python?
Just above we encountered the termAsynchronous. What does it mean?
For simple understanding, it just means thatnot occurring at the same time. It is theoretical meaning. We gonna learn the Practical definition ofasynchronous ahead of this article with an example that lets you understand it easily.
asyncio
- Asynchronous IO :
We cannot useasync
/await
syntax directly in the function to make it asynchronous rather we can use a Python packageasyncio
to achieve the goal.
Before diving into theasyncio module let's understandAsynchronous IO first.
note: I refer to asynchronous IO as async IO and
asyncio
is a Python package.
Asynchronous IO :
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 gonna 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 andasynchronously.
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 plays one game at a time, never moves to the next game until the current game is completed. Each game takes(55 + 5) 30 = 1800 seconds* or30 minutes. The entire exhibition takes24*30 = 720 minutes or12 hours.
Asynchronous approach:
In this approach, Judit moves table to table, making one move at each table. After making each move she leaves the table and lets the opponent make their next move during the wait time.
One move on all 24 games takes Judit Polgár24*5 = 120 seconds or 2 minutes. So, the entire exhibition is now cut down to120*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 allows other tasks to run during that downtime.
TheSource of this example.
Let's move to the next part of this article.
Python'sasyncio
module :
According to documentation,asyncio
is a type of library that helps us to write concurrent code usingasync
/await
syntax.
Since it's a module we have to import it.
importasyncio
asyncio
works withCoroutines. 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 theasync/await syntax is the preferred way of writingasyncio applications.
Here's the simple use case:
importasyncioasyncdeffunc():print("Hey....")awaitasyncio.sleep(1)print("I am here...")asyncio.run(func())
async def func()
-We usedasync
to make the function asynchronous.await asyncio.sleep(1)
-Here, we usedawait
and used theasyncio.sleep()
to delay the execution ofprint
statement below it.asyncio.run(func())
-Finally we are calling the function. You can see that we usedasyncio
to call the function, if we try to call the function simply as usual then we get aRuntimeError
.
- Note: You must be on Python 3.7 or above.
Until here, you surely get some idea onAsynchronous IO andasyncio use case.
Let's look at the examples demonstrating theAsynchronous function:
Asynchronous
importasyncioasyncdefwrite():print("Hey")awaitasyncio.sleep(1)print("there")asyncdefmain():awaitasyncio.gather(write(),write(),write())if__name__=="__main__":importtimestart=time.perf_counter()asyncio.run(main())elapsed=time.perf_counter()-startprint(f"File executed in{elapsed:0.2f} seconds")
We created two
async
functions -First is the
write()
function that printsHey
then wait for 1 second and then again printsthere
.Second is
main()
function that executeswrite()
function 3 times usingasyncio.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 aSynchronous way:
Synchronous
importtimedefwrite():print("Hey")time.sleep(1)print("there")defmain():for_inrange(3):write()if__name__=="__main__":start=time.perf_counter()main()elapsed=time.perf_counter()-startprint(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 the approaches and even understand how it's happened.
Conclusion
We can useasync
/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✌✌
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse