Asíncrono/Espera en Python
La programación asíncrona permite la ejecución simultánea sin subprocesos, ideal para tareas vinculadas a E/S.
Conceptos básicos
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())
Ejecutar tareas simultáneamente
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()
)
Ejemplo del mundo real: solicitudes HTTP
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())
Cuándo utilizar asíncrono
Bueno para: - solicitudes HTTP - Consultas de bases de datos. - E/S de archivos - WebSockets
No es ideal para:
- Tareas vinculadas a la CPU (use multiprocessing)
- Scripts simples con E/S mínima