Middle
What is the keyword 'await' in Python and how is it used?
sobes.tech AI
Answer from AI
The keyword await is used in asynchronous programming to wait for the completion of an awaitable object, such as a coroutine. It can only be used inside an asynchronous function defined with async def.
When await is encountered:
- The execution of the coroutine is suspended at that point.
- Control is returned to the event loop (event loop), which can run other tasks (coroutines).
- After the awaitable object completes, the suspended coroutine resumes from where it left off.
import asyncio
async def task1():
print("Executing Task 1")
await asyncio.sleep(1) # Waits for sleep to finish without blocking the event loop
print("Task 1 Finished")
async def task2():
print("Executing Task 2")
await asyncio.sleep(2) # Waits for sleep to finish
print("Task 2 Finished")
async def main():
# await is used to wait for individual coroutines to finish
await task1()
await task2()
# Running the asynchronous program
# asyncio.run(main())
In this example, await asyncio.sleep(1) suspends task1, allowing task2 to start executing. After sleep(1) completes, task1 resumes. await enables non-blocking execution of asynchronous code.