Async Function Patterns
Defining Async Functions
Basic Async Function
import asyncio
async def fetch_data(url):
await asyncio.sleep(1) ## Simulating network request
return f"Data from {url}"
Common Async Patterns
1. Sequential Execution
async def sequential_tasks():
result1 = await fetch_data('url1')
result2 = await fetch_data('url2')
return [result1, result2]
2. Concurrent Execution
async def concurrent_tasks():
## Run tasks concurrently
results = await asyncio.gather(
fetch_data('url1'),
fetch_data('url2')
)
return results
Task Management
Creating and Managing Tasks
async def task_management():
## Create tasks
task1 = asyncio.create_task(fetch_data('url1'))
task2 = asyncio.create_task(fetch_data('url2'))
## Wait for specific tasks
await task1
await task2
Async Context Managers
Implementing Context Managers
import asyncio
class AsyncResource:
async def __aenter__(self):
print("Acquiring resource")
await asyncio.sleep(1)
return self
async def __aexit__(self, exc_type, exc, tb):
print("Releasing resource")
await asyncio.sleep(1)
async def use_async_context():
async with AsyncResource() as resource:
## Perform operations
pass
Async Iteration
Async Generator
async def async_generator():
for i in range(5):
await asyncio.sleep(1)
yield i
async def process_async_generator():
async for item in async_generator():
print(item)
Error Handling Patterns
Comprehensive Error Handling
async def robust_async_function():
try:
result = await potentially_failing_operation()
except Exception as e:
## Specific error handling
return None
else:
return result
Async Function Flow
graph TD
A[Start Async Function] --> B{Async Operation}
B --> |Success| C[Return Result]
B --> |Error| D[Handle Exception]
C --> E[End Function]
D --> E
Async Patterns Comparison
Pattern |
Use Case |
Complexity |
Performance |
Sequential |
Simple dependencies |
Low |
Slower |
Concurrent |
Independent tasks |
Medium |
Faster |
Task Management |
Complex workflows |
High |
Optimized |
Best Practices
- Use
asyncio.gather()
for concurrent operations
- Implement proper error handling
- Avoid blocking operations in async functions
- Use async context managers for resource management
Note: LabEx recommends practicing these patterns to master asynchronous programming in Python.
Advanced Pattern: Async Semaphore
async def limited_concurrent_tasks():
semaphore = asyncio.Semaphore(3) ## Limit to 3 concurrent tasks
async with semaphore:
await fetch_data('url')
By understanding and implementing these async function patterns, developers can create more efficient and responsive Python applications.