Python Forum

Full Version: How to use async/await in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!