What is Async and Await in Python With Example?

In Python, the async keyword is used to define a coroutine function, which allows for asynchronous programming. Async functions are used to perform tasks concurrently and can be suspended and resumed during execution, allowing other tasks to run in the meantime.

Here’s an example that demonstrates the use of async in Python:

import asyncio

async def count_down(name, count):
    while count > 0:
        print(f'{name}: {count}')
        await asyncio.sleep(1)  # Await the sleep coroutine
        count -= 1

async def main():
    # Create two tasks that will run concurrently
    task1 = asyncio.create_task(count_down('Task 1', 5))
    task2 = asyncio.create_task(count_down('Task 2', 3))

    # Wait for both tasks to complete
    await asyncio.gather(task1, task2)

asyncio.run(main())
Code language: Python (python)

In this example, we define an async function called count_down that takes a name and a count as parameters. It prints the count value and then suspends execution for one second using the await asyncio.sleep(1) statement. This allows other tasks to run during the sleep period. The count is decremented in each iteration until it reaches zero.

The main function creates two tasks using asyncio.create_task() to run the count_down coroutine concurrently. The asyncio.gather() function is used to wait for both tasks to complete before the program exits.

By using async and await, we can write asynchronous code that appears synchronous and allows for better utilization of system resources when dealing with I/O-bound tasks or parallel processing.

Read More;

  • I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment