Skip to content

AsyncIO & The Event Loop

⚡ AsyncIO & The Event Loop

For I/O-bound tasks (network calls, database queries), AsyncIO is the standard for non-blocking execution in Python.


🏗️ 1. The Event Loop

The Event Loop is the engine that manages and executes asynchronous tasks. It waits for I/O events and switches between tasks without blocking.

How it works:

  • Coroutines: Defined with async def.
  • Awaiting: Use await to yield control back to the loop while waiting for a task.
import asyncio

async def fetch_data(id: int):
    print(f"Fetching data {id}...")
    await asyncio.sleep(1)  # Simulate I/O
    print(f"Data {id} fetched!")
    return {"id": id, "data": "value"}

async def main():
    # Run multiple tasks concurrently
    results = await asyncio.gather(
        fetch_data(1),
        fetch_data(2),
        fetch_data(3)
    )
    print(results)

if __name__ == "__main__":
    asyncio.run(main())

📦 2. Aiohttp for Network I/O

Standard requests is blocking. For AsyncIO, use aiohttp or httpx.

import aiohttp
import asyncio

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.json()

async def main():
    async with aiohttp.ClientSession() as session:
        result = await fetch_url(session, "https://api.example.com/data")
        print(result)

asyncio.run(main())

🚦 3. Task Management & Exceptions

Managing many tasks requires robust error handling and cancellation.

Key Tools:

  • asyncio.create_task(): Start a coroutine in the background.
  • asyncio.wait_for(): Add a timeout to a task.
  • asyncio.shield(): Protect a task from cancellation.