Python Forum
[Advanced] How to use async/await in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Advanced] How to use async/await in Python
#1
How to use async/await in Python
In asynchronous programming, the async and await keywords are used to create and manage coroutines.
  • The async keyword creates coroutine function.
  • The await keyword is used inside of a coroutine function to wait for the execution of another coroutine.

Create a coroutine
Defining a coroutine function is just like defining regular functions, except that the definition starts with async def instead of just def.
example:
async def add(a, b):
    print(f'{a} + {b} = {a + b}')
To execute a coroutine, we use the asyncio.run() function.
import asyncio

async def add(a, b):
    print(f'{a} + {b} = {a + b}')

#create a coroutine object
coro = add(10, 20) 

#run the coroutine
asyncio.run(coro) #executes the code in the coroutine
Output:
10 + 20 = 30
Execute a coroutine inside of another coroutine
The await keywords pauses a coroutine, until another coroutine is fully executed.
It has the following syntax:
await coro
Consider the following example:
import asyncio

#prints even numbers from 0-n
async def display_evens(n):
    for i in range(n):
        if i % 2 == 0:
            print(i)

async def main():
      print("Started!")
      await display_evens(10) #await display_evens()
      print('Finished!')

#run main
asyncio.run(main())
Output:
Started! 0 2 4 6 8 Finished!
Larz60+ write Apr-01-2024, 09:07 AM:
clickbait links removed
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020