await keyword is used to pause the execution of a task until the result of another task or operation is ready. It's a key part of Python's asynchronous programming, allowing for non-blocking, concurrent execution of I/O-bound tasks.
import asyncio
async def fun():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(fun())
Output
Hello World
Explanation:
- await asyncio.sleep(1) pauses the execution for 1 second without blocking other tasks, allowing the event loop to run other asynchronous operations.
- After the pause, print("World") executes, demonstrating the non-blocking behavior enabled by await.
Syntax
await <expression>
- Parameters: expression - An awaitable object, such as a coroutine, an asynchronous function, or any object that supports asynchronous operations (e.g., asyncio.sleep(), a Future object).
- Returns: It returns the result of the awaited task or coroutine once it has finished executing.
Examples
Example 1: This example demonstrates how to run two tasks concurrently using Python's asyncio library.
import asyncio
async def task_1():
print("Task 1 started")
await asyncio.sleep(2)
print("Task 1 completed")
async def task_2():
print("Task 2 started")
await asyncio.sleep(1)
print("Task 2 completed")
async def main():
await asyncio.gather(task_1(), task_2())
asyncio.run(main())
Output
Task 1 started Task 2 started Task 2 completed Task 1 completed
Explanation:
- asyncio.gather() starts both coroutines concurrently.
- Since task_2() waits for 1 second and task_1() waits for 2 seconds, task_2() completes first, followed by task_1().
- This demonstrates how await allows multiple asynchronous tasks to make progress without blocking each other.
Example 2: This example shows how await can be used to execute asynchronous tasks one after another. The second task starts only after the first task finishes.
import asyncio
async def custom_async_task(task_num):
print(f"Task {task_num} started")
await asyncio.sleep(3)
print(f"Task {task_num} completed")
async def main():
await custom_async_task(1)
await custom_async_task(2)
asyncio.run(main())
Output
Task 1 started
Task 1 completed
Task 2 started
Task 2 completed
Explanation:
- await custom_async_task(1) pauses main() until Task 1 completes.
- Only then does await custom_async_task(2) start Task 2.
- Although the tasks are asynchronous, they execute sequentially because each task is awaited before the next one begins.