Async/Await in Python

Understanding Python's async/await for concurrent programming with asyncio

Async/Await in Python

Async programming allows concurrent execution without threads, ideal for I/O-bound tasks.

Basic Concepts

import asyncio

async def fetch_data() -> str:
    await asyncio.sleep(1)  # Simulates I/O
    return "data"

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

Running Tasks Concurrently

async def main():
    # Sequential - takes 3 seconds
    a = await fetch_data()
    b = await fetch_data()
    c = await fetch_data()

    # Concurrent - takes 1 second
    a, b, c = await asyncio.gather(
        fetch_data(),
        fetch_data(),
        fetch_data()
    )

Real-World Example: HTTP Requests

import aiohttp
import asyncio

async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = [
        "https://api.example.com/users",
        "https://api.example.com/posts",
        "https://api.example.com/comments",
    ]

    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(
            *[fetch_url(session, url) for url in urls]
        )

    for result in results:
        print(len(result))

asyncio.run(main())

When to Use Async

Good for: - HTTP requests - Database queries - File I/O - WebSockets

Not ideal for: - CPU-bound tasks (use multiprocessing) - Simple scripts with minimal I/O