Python await keyword

python await keyword

Python await keyword is used to pause or suspend a coroutine from running in Python programming.

The await keyword is used within an asynchronous function to indicate that a specific coroutine or awaitable object should be awaited.

When the await keyword is encountered, the function temporarily suspends its execution until the awaited object completes its task.

During this suspension, the event loop regains control and can schedule other tasks for execution, resulting in highly efficient and non-blocking code execution.

Inside the asynchronous function, you can use the await keyword followed by an awaitable object.

For instance:

async def my_async_function():
    result = await awaitable_expression

Here are a few examples of using the await keyword in Python.

These examples demonstrate the use of the await keyword to pause the execution of an asynchronous function until a particular task, such as waiting for a timeout or completing an I/O operation, is finished.

Example 1: Asynchronous Function with await

import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(1)
    print("World!")

async def main():
    await greet()

asyncio.run(main())

Output:

Hello
World!

In this example, the greet() function is defined as an asynchronous function using the async keyword.

Inside the function, the await keyword is used to pause the execution of the function and asynchronously wait for 1-second using asyncio.sleep().

This allows other tasks to run concurrently.

The main() function is also defined as an asynchronous function, and it calls the greet() function using await.

Example 2: A timed loop with await

import asyncio

async def counting():
    for num in range(1,11):
        print(num)
        await asyncio.sleep(1)

asyncio.run(counting())

Output:

1
2
3
4
5
6
7
8
9
10

In the above example, the await keyword is used together with asyncio.sleep() method to cause a 1-second delay in the for loop operation.

Conclusion

The await keyword in Python unlocks the potential of asynchronous programming, enabling you to write efficient, non-blocking code that can execute multiple tasks concurrently.


Leave a Reply

Your email address will not be published. Required fields are marked *