async-python-patterns
Qué hace
Te ayuda a crear programas en Python más rápidos y eficientes. Permite que el programa haga varias cosas a la vez sin congelarse, sobre todo cuando necesita esperar algo (como datos de internet).
Cuándo usarla
- ✓Al crear sitios web o apps que necesitan responder rápido.
- ✓Al descargar mucha información de internet al mismo tiempo.
- ✓Para que el programa espere algo sin detener todo lo demás.
Link de la skill
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/async-python-patterns/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“¿Cómo puedo hacer que mi programa en Python descargue varias páginas web al mismo tiempo?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
Usa un 'bucle de eventos' para gestionar las tareas. Cuando una tarea necesita esperar, el bucle pasa a otra. Las palabras clave `async` y `await` ayudan a organizar esas pausas y reanudaciones.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
Async Python Patterns
Comprehensive guidance for implementing asynchronous Python applications using asyncio, concurrent programming patterns, and async/await for building high-performance, non-blocking systems.
When to Use This Skill
- Building async web APIs (FastAPI, aiohttp, Sanic)
- Implementing concurrent I/O operations (database, file, network)
- Creating web scrapers with concurrent requests
- Developing real-time applications (WebSocket servers, chat systems)
- Processing multiple independent tasks simultaneously
- Building microservices with async communication
- Optimizing I/O-bound workloads
- Implementing async background tasks and queues
Sync vs Async Decision Guide
Before adopting async, consider whether it's the right choice for your use case.
| Use Case | Recommended Approach |
|---|---|
| Many concurrent network/DB calls | asyncio |
| CPU-bound computation | multiprocessing or thread pool |
| Mixed I/O + CPU | Offload CPU work with asyncio.to_thread() |
| Simple scripts, few connections | Sync (simpler, easier to debug) |
| Web APIs with high concurrency | Async frameworks (FastAPI, aiohttp) |
Key Rule: Stay fully sync or fully async within a call path. Mixing creates hidden blocking and complexity.
Core Concepts
1. Event Loop
The event loop is the heart of asyncio, managing and scheduling asynchronous tasks.
Key characteristics:
- Single-threaded cooperative multitasking
- Schedules coroutines for execution
- Handles I/O operations without blocking
- Manages callbacks and futures
2. Coroutines
Functions defined with async def that can be paused and resumed.
Syntax:
async def my_coroutine():
result = await some_async_operation()
return result
3. Tasks
Scheduled coroutines that run concurrently on the event loop.
4. Futures
Low-level objects representing eventual results of async operations.
5. Async Context Managers
Resources that support async with for proper cleanup.
6. Async Iterators
Objects that support async for for iterating over async data sources.
Quick Start
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1)
print("World")
# Python 3.7+
asyncio.run(main())
Fundamental Patterns
Pattern 1: Basic Async/Await
import asyncio
async def fetch_data(url: str) -> dict:
"""Fetch data from URL asynchronously."""
await asyncio.sleep(1) # Simulate I/O
return {"url": url, "data": "result"}
async def main():
result = await fetch_data("https://api.example.com")
print(result)
asyncio.run(main())
Pattern 2: Concurrent Execution with gather()
import asyncio
from typing import List
async def fetch_user(user_id: int) -> dict:
"""Fetch user data."""
await asyncio.sleep(0.5)
return {"id": user_id, "name": f"User {user_id}"}
async def fetch_all_users(user_ids: List[int]) -> List[dict]:
"""Fetch multiple users concurrently."""
tasks = [fetch_user(uid) for uid in user_ids]
results = await asyncio.gather(*tasks)
return results
async def main():
user_ids = [1, 2, 3, 4, 5]
users = await fetch_all_users(user_ids)
print(f"Fetched {len(users)} users")
asyncio.run(main())
Pattern 3: Task Creation and Management
import asyncio
async def background_task(name: str, delay: int):
"""Long-running background task."""
print(f"{name} started")
await asyncio.sleep(delay)
print(f"{name} completed")
return f"Result from {name}"
async def main():
# Create tasks
task1 = asyncio.create_task(background_task("Task 1", 2))
task2 = asyncio.create_task(background_task("Task 2", 1))
# Do other work
print("Main: doing other work")
await asyncio.sleep(0.5)
# Wait for tasks
result1 = await task1
result2 = await task2
print(f"Results: {result1}, {result2}")
asyncio.run(main())
Pattern 4: Error Handling in Async Code
import asyncio
from typing import List, Optional
async def risky_operation(item_id: int) -> dict:
"""Operation that might fail."""
await asyncio.sleep(0.1)
if item_id % 3 == 0:
raise ValueError(f"Item {item_id} failed")
return {"id": item_id, "status": "success"}
async def safe_operation(item_id: int) -> Optional[dict]:
"""Wrapper with error handling."""
try:
return await risky_operation(item_id)
…
Preguntas frecuentes
¿Cuál es la diferencia entre 'sync' y 'async'?
'Sync' (síncrono) es como una carretera de un solo carril: un coche a la vez. 'Async' (asíncrono) es como una autopista de varios carriles: los coches pueden avanzar al mismo tiempo, y algunos pueden esperar un poco sin bloquear a los demás.
¿Qué es una 'corrutina'?
Es una función especial de Python (marcada con `async def`) que puede pausarse y reanudarse, lo que permite al programa hacer otras cosas mientras espera.
¿Cuándo NO debo usar 'async'?
Si tu programa hace mucho cálculo pesado (en vez de esperar red o disco), usar 'async' puede no ayudar e incluso complicar las cosas. En esos casos, otras técnicas pueden ser mejores.
Detalles
Descripción original del autor
Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.
repo: wshobson/agents
Popularidad
- Estrellas en GitHub
- 41 mil
- Posición en el ranking
- #6755
- Licencia
- MIT
- Actualizada
- 15/10/2026
Comentarios
- …
Más skills de este repositorio
screen-reader-testing
41 milHace que tu agente pruebe sitios web con lectores de pantalla para comprobar que son accesibles.
wcag-audit-patterns
41 milAyuda a tu agente a auditar la accesibilidad de sitios web y a corregir problemas según las pautas WCAG.
multi-reviewer-patterns
41 milPermite a tu agente coordinar revisiones de código en paralelo, eliminando hallazgos duplicados y consolidando los informes.
parallel-debugging
41 milPermite a tu agente depurar problemas complejos con investigaciones en paralelo y análisis de causa raíz.
Skills parecidas
api-connector-builder
280 milHace que tu agente cree nuevas conexiones de API siguiendo el patrón existente. Úsalo para añadir una integración más sin inventar otra forma de hacer las cosas.
api-design
280 milAyuda a tu agente a diseñar APIs REST según las buenas prácticas. Es útil para definir cómo se comunican las APIs, cómo se muestran los errores y cómo organizar los datos.
backend-patterns
280 milAyuda a tu agente con patrones de arquitectura del lado del servidor y optimización de bases de datos. Es útil para crear o revisar código que se ejecuta en el servidor.