python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# Python Async/Await Comprehensive Guide
import asyncio
import aiohttp
import time
from typing import List
# 1. Basic async function
async def fetch_data(url: str) -> dict:
"""Asynchronously fetch data from a URL."""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
# 2. Concurrent execution with gather
async def fetch_multiple_urls(urls: List[str]) -> List[dict]:
"""Fetch multiple URLs concurrently."""
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
return results
# 3. Async context manager
class DatabaseConnection:
async def __aenter__(self):
print("Connecting to database...")
await asyncio.sleep(0.1) # Simulate connection delay
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
print("Closing database connection...")
await asyncio.sleep(0.1)
async def query(self, sql: str):
await asyncio.sleep(0.05)
return f"Results for: {sql}"
# 4. Using async context manager
async def database_operation():
async with DatabaseConnection() as db:
result = await db.query("SELECT * FROM users")
print(result)
# 5. Async generator for streaming data
async def async_range(start: int, end: int):
"""Async generator that yields numbers with delay."""
for i in range(start, end):
await asyncio.sleep(0.1)
yield i
# 6. Consuming async generator
async def process_stream():
async for value in async_range(0, 5):
print(f"Processing: {value}")
# 7. Task management and cancellation
async def long_running_task(name: str):
try:
print(f"Task {name} started")
await asyncio.sleep(5)
print(f"Task {name} completed")
except asyncio.CancelledError:
print(f"Task {name} was cancelled")
raise
async def manage_tasks():
task1 = asyncio.create_task(long_running_task("A"))
task2 = asyncio.create_task(long_running_task("B"))
await asyncio.sleep(1)
task1.cancel() # Cancel task after 1 second
try:
await asyncio.gather(task1, task2, return_exceptions=True)
except asyncio.CancelledError:
pass
# 8. Rate limiting with semaphore
async def limited_fetch(url: str, semaphore: asyncio.Semaphore):
async with semaphore:
return await fetch_data(url)
async def fetch_with_rate_limit(urls: List[str], max_concurrent: int = 5):
"""Fetch URLs with concurrency limit."""
semaphore = asyncio.Semaphore(max_concurrent)
tasks = [limited_fetch(url, semaphore) for url in urls]
return await asyncio.gather(*tasks)
# 9. Main execution pattern
async def main():
# Sequential execution
start = time.time()
result1 = await fetch_data("https://api.example.com/1")
result2 = await fetch_data("https://api.example.com/2")
print(f"Sequential: {time.time() - start:.2f}s")
# Concurrent execution (much faster!)
start = time.time()
results = await asyncio.gather(
fetch_data("https://api.example.com/1"),
fetch_data("https://api.example.com/2")
)
print(f"Concurrent: {time.time() - start:.2f}s")
# Run the async program
if __name__ == "__main__":
asyncio.run(main())