Python - Async Programming
What is Asynchronous Programming?
Asynchronous programming allows a program to handle many tasks concurrently by pausing and resuming functions using async and await. It’s useful for I/O-bound tasks such as web requests or file operations.
Why Use Async Programming?
- Efficient use of I/O operations
- Non-blocking execution
- Better performance in network-heavy apps
Basic async/await Syntax
python
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(greet())
Running Multiple Tasks Concurrently
python
import asyncio
async def task(name, delay):
await asyncio.sleep(delay)
print(f"Finished {name}")
async def main():
await asyncio.gather(
task("A", 1),
task("B", 2),
task("C", 1)
)
asyncio.run(main())
Using async with HTTP Requests (aiohttp)
python
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
html = await fetch("https://example.com")
print(html[:100]) # Print first 100 characters
asyncio.run(main())
Difference Between Threading and Async
- Threading: Multiple OS threads; used for I/O or CPU-bound tasks
- Async: Single-threaded, cooperative multitasking; best for I/O-bound operations
When to Use Async
- When making multiple API calls
- When doing non-blocking operations (e.g., disk/network I/O)
- When building real-time apps (chat, streaming, etc.)
Pros and Cons
| Pros | Cons |
|---|---|
| Efficient for I/O | Harder to debug |
| Low memory usage | Not suitable for CPU-bound tasks |
| Improved responsiveness | Requires async-compatible libraries |
Conclusion
Python's asynchronous programming using asyncio and await enables writing efficient, concurrent code, particularly for I/O-heavy operations like APIs and file handling. It’s an essential technique for modern Python developers building responsive applications.