Python async keyword

Python async keyword is used to specify that a given function is a coroutine in Python programming.

The async keyword indicates a function as a coroutine and a coroutine is a special type of function that can be paused and resumed during execution. When a function is defined with the async keyword, it becomes a coroutine function.

Coroutines provide a convenient way to write asynchronous code, making it easier to handle concurrent operations and coordinate their execution.

However, to use the async keyword, you must first import the asyncio module.

Example 1: Creating a simple coroutine

import asyncio

async def greeting():
    print('hello')

asyncio.run(greeting())

Output:

hello

In the above example, the async keyword is used to indicate that the function greeting() is a coroutine.

Example 2: Simple Asynchronous Function

import asyncio

async def greet(name):
    print("Hello, " + name)
    await asyncio.sleep(1) 
    print("Goodbye, " + name)

async def main():
    await greet("Kate")
    await greet("Brian")

asyncio.run(main())

Output:

Hello, Kate
Goodbye, Kate
Hello, Brian
Goodbye, Brian

In this example, the greet() function is defined as an asynchronous function using the async def syntax. It prints a greeting message, awaits the asyncio.sleep() function, and then prints a goodbye message.

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

Using await for Asynchronous Operations

Inside the coroutine, you can use other coroutines and await expressions to pause the execution until a particular task completes. This multitasking approach allows the interpreter to switch between coroutines without blocking the program’s execution.

Let’s take a simple example to demonstrate the usage of async and await. Suppose we want to fetch the contents of multiple web pages concurrently.

import asyncio

async def task1():
    print("Executing Task 1")
    await asyncio.sleep(1)
    print("Task 1 Completed")

async def task2():
    print("Executing Task 2")
    await asyncio.sleep(2)
    print("Task 2 Completed")

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

Output:

Executing Task 1
Executing Task 2
Task 1 Completed
Task 2 Completed

In the above example, two asynchronous tasks, task1() and task2()were defined. The main() function uses asyncio.gather() to run both tasks concurrently, ensuring that they execute in parallel.

Conclusion

Python’s async keyword, along with the await keyword, provides you with a powerful mechanism to write efficient asynchronous code.

By leveraging coroutines and cooperative multitasking, Python makes it easier to handle concurrent tasks and improves the overall responsiveness of applications.

Asynchronous programming is particularly valuable in scenarios where tasks involve time-consuming operations such as network communication or I/O-bound operations. By utilizing the async and await keywords, developers can harness the power of asynchronous execution while maintaining clean and readable code.

Leave a Reply

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