Movatterモバイル変換


[0]ホーム

URL:


Open In App

asynckeyword inPython is used to defineasynchronous 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 onawait 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 theasyncio library, to know about it in detail, refer toasyncio in Python. Let's consider an example.

Python
importasyncioasyncdeffunc():print("Hello!")awaitasyncio.sleep(2)# Pause for 2 second without blockingprint("Geeks for Geeks")#asyncio.run(func())

Output
Hello!Geeks for Geeks

Explanation:

  • "async" keyword before "def" keyword defines the function func as an asynchronous function.
  • "await asyncio.sleep(2)" makes it wait for 2 second before continuing.
  • that's why when the function is called using "asyncio.run(gree())", the second print statement gets executed after a delay of 2 seconds.

Syntax:

async def function_name():
await some_async_function()

  • async def:defines an asynchronous function.
  • await:pauses execution until the awaited function completes.

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

Running Multiple Tasks Simultaneously

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

Python
importasyncioasyncdeftask1():print("Task 1 started")awaitasyncio.sleep(3)print("Task 1 finished")asyncdeftask2():print("Task 2 started")awaitasyncio.sleep(1)print("Task 2 finished")asyncdefmain():awaitasyncio.gather(task1(),task2())# Runs both tasks togetherasyncio.run(main())

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

Explanation:

  • in this code,task1()andtask2() 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 is a very common practice to use async keyword withHTTP 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
importaiohttpimportasyncioasyncdeffunc():asyncwithaiohttp.ClientSession()assession:asyncwithsession.get("https://example.com/")asres:data=awaitres.text()print(data[:100])# Prints first 100 charactersasyncio.run(func())

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

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:

  • aiohttplibrary is used for making asyncHTTP requests.
  • aiohttp.ClientSession(),createsHTTP session and making an asynchronous get request usingsession.get().
  • awaitkeyword 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 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 usingasyncio.sleep() to represent delays, similar to real-world scenarios where I/O operations take time. Here's an example:

Python
importasyncioimportaiofilesimportasyncioasyncdefwrite():asyncwithaiofiles.open(r"paste_your_file_path_here\file.txt","w")asf:awaitf.write("Hello from Geeks for Geeks!")asyncdefread():asyncwithaiofiles.open(r"paste_your_file_path_here\file.txt","r")asf:print(awaitf.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 aFileNotFoundError.
  • 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 Python in detail, refer to-File Handling In Python


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp