advancedAdvanced Topics
Async Programming
Write concurrent code with async/await for I/O-bound tasks.
In this lesson
01Async Basics
Use async def and await for non-blocking I/O operations.
Python
1import asyncio23async def fetch_data(url: str, delay: float):4 print(f"Fetching {url}...")5 await asyncio.sleep(delay) # simulates I/O6 return f"Data from {url}"78async def main():9 # Run concurrently10 results = await asyncio.gather(11 fetch_data("api/users", 1.0),12 fetch_data("api/posts", 0.5),13 fetch_data("api/comments", 0.8),14 )15 for r in results:16 print(r)1718asyncio.run(main())
Output
Fetching api/users... Fetching api/posts... Fetching api/comments... Data from api/users Data from api/posts Data from api/comments