PythonSyntax and keywords
async and await
Asynchronous programming: waiting for operations without blocking the whole program.
Example
#Python
import asyncio
async def load(name, delay):
await asyncio.sleep(delay)
return f"{name} ready"
async def main():
results = await asyncio.gather(
load("courses", 0.2),
load("profile", 0.1)
)
print(results)
asyncio.run(main())Resultsaved result, you can check it
['courses ready', 'profile ready']
Definition and usage
#A function defined with async def is a coroutine. Inside it, await pauses its execution until another asynchronous operation finishes, letting other tasks run in the meantime.
Coroutines are run by an event loop, most simply with asyncio.run(main()). The asyncio.gather() function runs several coroutines at once and waits for all of them, which speeds up things like multiple network requests.
Asynchrony helps with operations that mostly wait: HTTP requests, databases, files. It will not speed up CPU-heavy computations.
Syntax
#Syntax
async def function():
result = await other_coroutine()Good practices
#asyncio.gather()returns results in the order the coroutines were passed in, not the order they finished.- Do not call blocking functions (e.g.
time.sleep) inside coroutines. Use their asynchronous equivalents instead.
Related entries
#Spotted a mistake or missing an example? Write to us.