Python async

Last Updated : 16 Jul, 2026

async keyword is used to define an asynchronous function. Such functions can pause while waiting for a task to complete, allowing other tasks to run without blocking the program.

Python
import asyncio

async def greet():
    print("Hello!")

    await asyncio.sleep(2)
    print("Welcome to Python!")

asyncio.run(greet())

Output
Hello!
Welcome to Python!

Explanation: statement async def greet() defines an asynchronous function. The expression await asyncio.sleep(2) pauses the function for 2 seconds without blocking the program. The function is executed using asyncio.run(greet()).

Syntax

async def function_name():
# Code

Parameters: function_name - name of the asynchronous function.

Running Multiple Tasks Simultaneously

With the help of async, multiple tasks can run without waiting for one to finish before starting another.

Python
import asyncio

async def task1():
    print("Task 1 started")
    await asyncio.sleep(3)
    print("Task 1 finished")

async def task2():
    print("Task 2 started")
    await asyncio.sleep(1)
    print("Task 2 finished")

async def main():
    await asyncio.gather(task1(), task2())  # Runs both tasks together

asyncio.run(main())

Output
Task 1 started 
Task 2 started 
Task 2 finished 
Task 1 finished

Explanation:

  • in this code, task1() and task2() run at the same time becasue they are defined as async functions.
  • task2() completes first because it waits for only 1 second, while task1() waits for 3 seconds.

Using Async with HTTP Requests

It's a very common practice to use async keyword with HTTP requests, if we fetch data from multiple URLs using a synchronous approach, each request blocks the execution until it completes. However, with async, we can send multiple requests simultaneously, making the program much faster. Here's an example:

Python
import aiohttp
import asyncio

async def func():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://example.com/") as res:
            data = await res.text()
            print(data[:100])  # Prints first 100 characters

asyncio.run(func())

Output
<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <m

Explanation: Here, we have defined an asynchronous function that performs an HTTP request using the async keyword, the breakdown of code is such:

  • aiohttp library is used for making async HTTP requests.
  • aiohttp.ClientSession(), creates HTTP session and making an asynchronous get request using session.get().
  • await keyword ensures that the request completes before proceeding to the next step.
  • data[:100] ensure that only first 100 characters are printed.

Note: Ensure that "aiohttp" library is installed on your system before running the code. If it's not installed, you can add it by running "pip install aiohttp" command in the terminal.

Using Async with File I/O

Python by default handles files one at a time, making the program wait until the task is done. But async can also be used for file operations. While writing and reading files, we can simulate async behavior using asyncio.sleep() to represent delays, similar to real-world scenarios where I/O operations take time. Here's an example:

Python
import asyncio
import aiofiles
import asyncio

async def write():
    async with aiofiles.open(r"paste_your_file_path_here\file.txt", "w") as f:
        await f.write("Hello from Geeks for Geeks!")

async def read():
    async with aiofiles.open(r"paste_your_file_path_here\file.txt", "r") as f:
        print(await f.read())

asyncio.run(write())
asyncio.run(read())

Output
Hello from Geeks for Geeks!

Explanation:

  • write_file() writes data to "file.txt" if it already exists in the specified path. If the file doesn't exist, it automatically creates a new "file.txt" and writes data to it.
  • read_file() opens "file.txt" in read mode and prints its content asynchronously. If the file doesn’t exist, it will raise a FileNotFoundError.
  • asyncio.run(write()) runs first, making sure the file is created and written. Then, asyncio.run(read()) runs, reading and printing the content.

To learn about file-handling in detail, refer to- File Handling

Comment