Async/Await en Python

La programación asíncrona permite ejecutar múltiples operaciones sin bloquear el hilo principal.

import asyncio

async def fetch_data(url): print(f"Fetching {url}...") await asyncio.sleep(1) return {"data": "resultado"}

async def main(): tasks = [fetch_data(f"https://api.example.com/{i}") for i in range(5)] results = await asyncio.gather(*tasks) print(results)

asyncio.run(main())

Conceptos Clave

  • Corrutinas: Funciones declaradas con async def
  • await: Suspende la ejecución hasta que el resultado esté listo
  • Event Loop: El coordinador central de todas las corrutinas
  • asyncio.gather(): Ejecuta múltiples corrutinas concurrentemente