[Advanced] How to use async/await in Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Tutorials (https://python-forum.io/forum-4.html) +---- Forum: Tutorial Requests and Submissions (https://python-forum.io/forum-21.html) +---- Thread: [Advanced] How to use async/await in Python (/thread-41877.html) |
How to use async/await in Python - pynerds - Apr-01-2024 How to use async/await in Python In asynchronous programming, the async and await keywords are used to create and manage coroutines.
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 Execute a coroutine inside of another coroutineThe await keywords pauses a coroutine, until another coroutine is fully executed. It has the following syntax: await coroConsider 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())
|