⚡ Python async/await — Asynchronous Programming Guide
asyncio enables concurrent I/O-bound tasks in Python without threads. Learn async/await to write high-performance APIs and web scrapers.
asyncio is for I/O-bound tasks (API calls, DB queries). For CPU-bound tasks, use multiprocessing instead.
💻 Code Example:
import asyncio import time # 1. Basic coroutine async def greet_pynfinity(name): await asyncio.sleep(1) # Non-blocking 1-second pause print(f"Hello, {name}!") # Run a single coroutine asyncio.run(greet_pynfinity("santoshtvk")) # 2. Run multiple tasks concurrently async def fetch_user(user_id): await asyncio.sleep(1) # Simulates network call return {'id': user_id, 'platform': 'pynfinity'} async def main(): start = time.time() # Concurrent — all 3 run SIMULTANEOUSLY (total ~1 second) results = await asyncio.gather( fetch_user(1), fetch_user(2), fetch_user(3), ) print(f"Fetched {len(results)} users in {time.time()-start:.2f}s") for r in results: print(r) asyncio.run(main()) # 3. Async context manager async def process_with_timeout(): try: async with asyncio.timeout(5.0): # Python 3.11+ await asyncio.sleep(2) return "Done within timeout" except asyncio.TimeoutError: return "Timed out!" print(asyncio.run(process_with_timeout()))
| Concept | Key Takeaway |
|---|---|
| async def | Define a coroutine function |
| await expr | Pause until the awaitable completes |
| asyncio.gather() | Run many coroutines concurrently |
| asyncio.run() | Run the top-level entry coroutine |
| asyncio.create_task() | Schedule coroutine without waiting now |
Keep exploring and happy coding! 🚀