Junior — Middle
Can you explain how asynchronous functions work using the keywords async and await in Python?
sobes.tech AI
Answer from AI
In Python, the keywords async and await are used to define and work with asynchronous functions, which allow performing input/output operations or other long-running tasks without blocking the main thread.
async defdeclares a function as asynchronous, which returns a coroutine.awaitis used inside an asynchronous function to suspend its execution until another coroutine or asynchronous operation completes.
This enables efficient management of waiting times, for example, during network requests, without blocking the execution of other tasks.
Example:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # simulate asynchronous delay
print("World")
async def main():
await say_hello()
asyncio.run(main())
In this example, say_hello is an asynchronous function that first prints "Hello", then waits for 1 second without blocking the thread, and then prints "World".