“async” and “await” Keywords in Python: An Introduction to Asynchronous Programming

"async" and "await" Keywords in Python: An Introduction to Asynchronous Programming

Asynchronous programming is widely used by developers for dealing with multiple tasks simultaneously. In traditional programming, the tasks are executed one by one in a sequential manner, but asynchronous programming allows you to execute multiple tasks independently. In Python, “async” and “await” are the two major keywords for executing asynchronous code. In this tutorial, we will discuss these keywords in detail, their usage, and how they help in writing better code.

Introduction to Asynchronous Programming

Asynchronous programming allows us to execute multiple tasks independently without blocking the main thread. In traditional programming, if we execute a slow task, the rest of the code will pause and wait for its completion, which can lead to delays and even hanging of the application in some cases. Asynchronous programming solves this issue by executing the slow task in the background, and then continuing the remaining code execution.

In other words, asynchronous programming schedules multiple tasks to run, and it does not wait for each task to complete before moving on to the next task. This allows the program to use system resources effectively and perform multiple tasks concurrently, which results in a significant improvement in performance, particularly when performing I/O-bound or network-bound operations.

“async” and “await” Keywords in Python

Python has introduced the “async” and “await” keywords in its latest versions to support asynchronous programming. By using these keywords, you can write asynchronous code that is easy to understand and maintain.

The “async” Keyword

The “async” keyword is used to define an asynchronous function in Python. By using the “async” keyword, you can define functions that can suspend and resume their execution, allowing other tasks to run while they wait for resources. The “async” function can be defined using the following syntax:

async def function_name(parameters):
    statement
    ...
    return result

In the above syntax, the “async” keyword is used to define the function as asynchronous, and the “def” keyword is used to define the function. The function’s name follows the “def” keyword, and the parameters are defined inside the parentheses. The body of the function contains the asynchronous code that runs when the function is called.

Example 1: Using the “async” Keyword

import asyncio

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

loop = asyncio.get_event_loop()
loop.run_until_complete(print_hello())

Output:

Hello
World

In the above example, we have defined an asynchronous function named “print_hello” using the “async” keyword. Inside the function, we have printed the string “Hello” and used the “await asyncio.sleep(1)” statement (where “await” is used to suspend the function’s execution) to suspend the function’s execution for 1 second. After 1 second, the function is resumed, and the string “World” is printed. At the end of the code, we have used the “run_until_complete()” function to run the asynchronous function.

The “await” Keyword

The “await” keyword is used to wait for the completion of an asynchronous function within another asynchronous function. The “await” keyword is used to suspend the execution of the current async function until the awaited async function completes its execution.

Example 2: Using the “await” Keyword

import asyncio

async def slow_function():
    await asyncio.sleep(1)
    return "Slow function completed"

async def fast_function():
    return "Fast function completed"

async def main():
    tasks = [slow_function(), fast_function()]
    completed_tasks = await asyncio.gather(*tasks)
    print(completed_tasks)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Output:

['Slow function completed', 'Fast function completed']

In the above example, we have defined three asynchronous functions: “slow_function”, “fast_function”, and “main”. The “slow_function” function contains an asynchronous task that takes 1 second to complete, while the “fast_function” function returns immediately. The “main” function uses the “asyncio.gather()” function to run both the functions concurrently and wait for their completion. The “completed_tasks” variable contains the return values of both the functions, which are printed on the console as a list.

Conclusion

Asynchronous programming is becoming increasingly popular among developers because it helps in executing multiple tasks simultaneously without blocking the main thread. In Python, “async” and “await” keywords help in writing asynchronous code that is easy to read, write, and maintain. By using asynchronous programming, you can improve the performance of your code and create better applications that are more responsive and efficient.

Leave a Reply

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