Explain asynchronous programming and its benefits.

 


Asynchronous Programming in Python

Python provides built-in support for asynchronous programming through the asyncio module, which enables efficient handling of I/O-bound operations like network requests, file handling, and database interactions.

1. Basic Example: Asynchronous Function with async/await

Here’s a simple example demonstrating an asynchronous function:

python
import asyncio
async def fetch_data():
print("Fetching data...")
await asyncio.sleep(2) # Simulating a network request
print("Data received!")
async def main():
print("Start")
await fetch_data() # Waits for fetch_data() to complete
print("End")
asyncio.run(main())  # Run the async function

πŸ”Ή Explanation:

  • async def defines an asynchronous function.
  • await asyncio.sleep(2) simulates a delay without blocking execution.
  • asyncio.run(main()) runs the asynchronous event loop.

πŸ’‘ Output:

sql
Start  
Fetching data...
(Data fetches after 2 seconds)
Data received!
End

2. Running Multiple Tasks Concurrently

Instead of waiting for one task to finish before starting another, we can execute multiple tasks at the same time using asyncio.gather().

python
import asyncio
async def fetch_data(id):
print(f"Fetching data for Task {id}...")
await asyncio.sleep(2)
print(f"Data received for Task {id}!")
async def main():
tasks = [fetch_data(1), fetch_data(2), fetch_data(3)] # Multiple tasks
await asyncio.gather(*tasks) # Run tasks concurrently
asyncio.run(main())

πŸ’‘ Output:

arduino
Fetching data for Task 1...
Fetching data for Task 2...
Fetching data for Task 3...
(Data fetches after 2 seconds)
Data received for Task 1!
Data received for Task 2!
Data received for Task 3!

πŸ”Ή Explanation:

  • asyncio.gather(*tasks) runs multiple asynchronous tasks simultaneously.
  • This approach significantly improves performance when handling multiple tasks.

3. Using Asynchronous HTTP Requests (aiohttp)

For real-world applications, network requests are a common use case for async programming. The aiohttp library enables non-blocking HTTP requests.

python
import asyncio
import aiohttp
async def fetch_url(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
print(f"Fetched {url} with status {response.status}")
async def main():
urls = [
"https://example.com",
"https://httpbin.org/get",
"https://jsonplaceholder.typicode.com/posts/1"
]
tasks = [fetch_url(url) for url in urls]
await asyncio.gather(*tasks) # Fetch multiple URLs concurrently
asyncio.run(main())

πŸ”Ή Explanation:

  • aiohttp makes non-blocking HTTP requests.
  • async with ensures proper resource management.
  • await asyncio.gather(*tasks) fetches multiple URLs concurrently.

When to Use Asynchronous Programming in Python?

Handling I/O-bound tasks — Web scraping, API calls, database operations.
Real-time applications — Chat apps, notifications, stock market monitoring.
Large file processing — Reading/writing large files without freezing execution.

WEBSITE: https://www.ficusoft.in/python-training-in-chennai/

Comments

Popular posts from this blog

Best Practices for Secure CI/CD Pipelines

What is DevSecOps? Integrating Security into the DevOps Pipeline

SEO for E-Commerce: How to Rank Your Online Store