await keyword in Python 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.
Python import asyncio # asynchronous function async def fun(): print("Hello") await asyncio.sleep(1) # Simulate an asynchronous task print("World") asyncio.run(fun()) # calling 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.
await Examples
Example 1: Mutiple coroutines with await
This example demonstrates how to run two tasks concurrently using Python's asyncio library.
Python import asyncio async def task_1(): print("Task 1 started") await asyncio.sleep(2) # Simulate a 2-second task print("Task 1 completed") async def task_2(): print("Task 2 started") await asyncio.sleep(1) # Simulate a 1-second task print("Task 2 completed") async def main(): await asyncio.gather(task_1(), task_2()) # Run both tasks concurrently asyncio.run(main())
Output
Task 1 started
Task 2 started
Task 1 completed
Task 2 completed
Explanation: task_1() and task_2() are asynchronous functions that print messages and pause for 2 and 1 second, respectively. The main() coroutine runs both tasks concurrently with asyncio.gather(). asyncio.run(main()) starts the event loop, running and waiting for both tasks to complete.
Example 2: await with custom async function
This example demonstrates how to process tasks sequentially using Python's asyncio library.
Python import asyncio async def custom_async_task(task_num): print(f"Task {task_num} started") await asyncio.sleep(3) # Simulate a 3-second task 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 : custom_async_task() simulates a 3-second task, printing its start and completion messages. The main() runs two tasks sequentially, waiting for one to finish before starting the next. asyncio.run(main()) executes both tasks, totaling around 6 seconds of runtime.
Similar Reads
aiter() in Python aiter() is a built-in function that returns an asynchronous iterator object from an asynchronous iterable. This allows us to iterate over asynchronous sequences, making it ideal for non-blocking operations in asynchronous programs. It is commonly used with async for loops to iterate over data that i
3 min read
anext() in Python anext() is a built-in function that retrieves the next item from an asynchronous iterator, acting as the async version of next(). It is essential when working with async iterators and generators, offering more flexibility in asynchronous workflows. Note: anext() is available starting in Python 3.10.
3 min read
asyncio in Python Asyncio is a Python library that is used for concurrent programming, including the use of async iterator in Python. It is not multi-threading or multi-processing. Asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web servers, databa
4 min read
Install Aiohttp In Python Aiohttp library in Python is an asynchronous HTTP client and server framework that is built on top of the asynchronous I/O library asyncio in Python. Using this library, we can build web applications and RESTful APIs, and also we can handle synchronous HTTP requests in the application. This library
2 min read
Coroutine in Python Prerequisite: GeneratorsWe all are familiar with function which is also known as a subroutine, procedure, sub-process, etc. A function is a sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided into several self-contained steps that are
5 min read