Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Async/Await: Asynchronous Programming In Python
Sachin
Sachin

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 useasyncwhich makes a function return a promise, andawaitwhich 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.

Synchronous & Asynchronous Diagram

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 andasyncio 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
Enter fullscreen modeExit fullscreen mode

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())
Enter fullscreen modeExit fullscreen mode
  1. async def func() -We usedasync to make the function asynchronous.

  2. await asyncio.sleep(1) -Here, we usedawait and used theasyncio.sleep() to delay the execution ofprint statement below it.

  3. 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")
Enter fullscreen modeExit fullscreen mode
  1. We created twoasync functions -

  2. First is thewrite() function that printsHey then wait for 1 second and then again printsthere.

  3. Second ismain() function that executeswrite() function 3 times usingasyncio.gather().

  4. And then we wrote a code that calculates the time taken to execute theasync functions.

Here's the output:

Asynchronous 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")
Enter fullscreen modeExit fullscreen mode

Here's the output:

Synchronous 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A Python developer obsessed with Machine Learning and Data Science.
  • Location
    Delhi
  • Joined

More fromSachin

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp