Python async (original) (raw)

Last Updated : 10 Mar, 2025

**async keyword in Python is used to define asynchronous functions, which allow tasks to run without blocking the execution of other code. It is commonly used for handling tasks like network requests, database operations or file I/O, where waiting for one task to finish would normally slow down the entire program. Async relies on await because an async function does not execute asynchronously on its own, it needs await to actually pause and resume tasks.

To use async in our code, we need to first import the asyncio library, to know about it in detail, refer to asyncio in Python. Let's consider an example.

Python `

import asyncio

async def func(): print("Hello!") await asyncio.sleep(2) # Pause for 2 second without blocking print("Geeks for Geeks") #

asyncio.run(func())

`

Output

Hello! Geeks for Geeks

**Explanation:

**Syntax:

async def function_name():
await some_async_function()

Let's see some of the use cases of the async with examples.

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:

Using Async with HTTP Requests

It is 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

Example Domain **Explanation: In this code we have defined an asynchronous function that performs an HTTP request using the async keyword, the breakdown of code is such:

**Note: Ensure that "aiohttp" library is installed on your system before running the code. If it's mot 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:

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