Python Async/Await — Asynchronous Programming
Async programming handles thousands of concurrent operations efficiently. It is essential for web servers, API clients, and real-time applications.
Learning Objectives
- Understand the event loop and coroutines
- Write async functions with async/await
- Use asyncio.gather for concurrent operations
- Build async context managers and generators
Basics
import asyncio
async def greet(name):
await asyncio.sleep(1) # Non-blocking sleep
return f"Hello, {name}"
result = asyncio.run(greet("Alice"))
Concurrent Operations
import asyncio
async def fetch(url):
print(f"Fetching {url}")
await asyncio.sleep(2)
return f"Data from {url}"
async def main():
urls = ["url1", "url2", "url3"]
tasks = [fetch(url) for url in urls]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Async HTTP with aiohttp
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ["https://example.com"] * 5
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
print(f"Fetched {len(results)} pages")
asyncio.run(main())
Async Context Managers
class AsyncDatabase:
async def __aenter__(self):
await self.connect()
return self
async def __aexit__(self, *args):
await self.disconnect()
async def main():
async with AsyncDatabase() as db:
await db.execute("SELECT * FROM users")
Key Takeaways
async defdefines a coroutineawaitpauses until the awaited coroutine completesasyncio.gather()runs multiple coroutines concurrently- Use for I/O-bound tasks (network, file, database)
- Not suitable for CPU-bound tasks (use multiprocessing)