Python asyncio: Mastering Async/Await Programming
Async programming in Python lets you handle thousands of concurrent operations without threads. Here's how to use asyncio effectively.
Complete Code Example
import asyncio
import httpx
from datetime import datetime
# Basic async function
async def fetch_price(symbol: str) -> float:
async with httpx.AsyncClient() as client:
r = await client.get(
"https://api.binance.com/api/v3/ticker/price",
params={"symbol": f"{symbol}USDT"}
)
return float(r.json()["price"])
# Running multiple tasks concurrently
async def fetch_all_prices():
symbols = ["BTC", "ETH", "SOL", "BNB"]
# Run all requests at the same time!
prices = await asyncio.gather(*[fetch_price(s) for s in symbols])
return dict(zip(symbols, prices))
# Async context manager
class AsyncTimer:
async def __aenter__(self):
self.start = datetime.now()
return self
async def __aexit__(self, *args):
elapsed = (datetime.now() - self.start).total_seconds()
print(f"Elapsed: {elapsed:.3f}s")
async def main():
async with AsyncTimer():
prices = await fetch_all_prices()
for symbol, price in prices.items():
print(f"{symbol}: ${price:,.2f}")
asyncio.run(main())
# Async generator
async def count_up(n: int):
for i in range(n):
await asyncio.sleep(0.01) # simulate async work
yield i
async def use_generator():
async for value in count_up(5):
print(value)
💡 Pro Tips
- Use asyncio.gather() to run multiple coroutines concurrently
- Never use time.sleep() in async code — use asyncio.sleep() instead
- httpx is the best async HTTP library for Python
Why This Matters
Understanding these Python features will help you write more:
- ✅ Readable and maintainable code
- ✅ Memory-efficient applications
- ✅ Pythonic, idiomatic solutions
Summary
Mastering Python's built-in features is key to becoming a better developer. Practice these examples in your own projects, and you'll quickly see the benefits.
Found this helpful? Follow me for more Python tutorials and tips! 🐍
Follow for more Python content!
📧 Get my FREE Python Cheatsheet → Follow me on Dev.to and drop a comment below — I'll DM you the cheatsheet directly!
🐍 50+ essential Python patterns, one-liners, and best practices for everyday development. Free for all readers.
喜欢这篇文章?关注获取更多Python自动化内容!
Now that you've mastered Python asyncio, you're one step closer to becoming a proficient Python developer. To help you take the next leap and land your dream job, I recommend checking out the Python Interview Prep Guide, which covers real-world scenarios and common interview questions. This guide has been curated based on actual developer experiences and tutorials, making it a valuable resource for anyone looking to improve their Python skills. With the Python Interview Prep Guide, you'll be well-prepared to tackle even the toughest interviews, and at $24.99, it's a worthwhile investment in your career.
Top comments (0)