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:
pythonimport asyncioasync 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
async defdefines an asynchronous function.await asyncio.sleep(2)simulates a delay without blocking execution.asyncio.run(main())runs the asynchronous event loop.
π‘ Output:
sqlStart
Fetching data...
(Data fetches after 2 seconds)
Data received!
End2. 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().
pythonimport asyncioasync 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())
arduinoFetching 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!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.
pythonimport asyncio
import aiohttpasync 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())
aiohttpmakes non-blocking HTTP requests.async withensures 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
Post a Comment