Pptx Visual Assets
38.8kÚsalo al seleccionar y colocar iconos, imágenes, SVGs, diagramas o infografías de apoyo aprobados en un PPTX editable.
- Costo de contexto al activarse
- 344 tok
- Tamaño del paquete
- 2 archivos
- Última actualización
- hace 26 días
Patrones de manejo de errores en Python: validación de entradas, jerarquías de excepciones y manejo de fallos parciales en lotes y APIs robustas.
en todo el repo
0–100, la ruta de este skill
último commit aquí
últimos 90 días
61 tok en reposo
11 KB
Funciona con cualquier agente que lea SKILL.md
npx -y skills add wshobson/agents --skill python-error-handling --agent claude-codeSe instala solo en este repositorio.
Di cualquiera de estas frases y el agente debería cargar este skill.
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
Validate inputs early, before expensive operations. Report all validation errors at once when possible.
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
In batch operations, don't let one failure abort everything. Track successes and failures separately.
Chain exceptions to maintain the full error trail for debugging.
def fetch_page(url: str, page_size: int) -> Page:
if not url:
raise ValueError("'url' is required")
if not 1 <= page_size <= 100:
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Now safe to proceed...
Validate all inputs at API boundaries before any processing begins.
def process_order(
order_id: str,
quantity: int,
discount_percent: float,
) -> OrderResult:
"""Process an order with validation."""
# Validate required fields
if not order_id:
raise ValueError("'order_id' is required")
# Validate ranges
if quantity <= 0:
raise ValueError(f"'quantity' must be positive, got {quantity}")
if not 0 <= discount_percent <= 100:
raise ValueError(
f"'discount_percent' must be 0-100, got {discount_percent}"
)
# Validation passed, proceed with processing
return _process_validated_order(order_id, quantity, discount_percent)
Parse strings and external data into typed domain objects at system boundaries.
from enum import Enum
class OutputFormat(Enum):
JSON = "json"
CSV = "csv"
PARQUET = "parquet"
def parse_output_format(value: str) -> OutputFormat:
"""Parse string to OutputFormat enum.
Args:
value: Format string from user input.
Returns:
Validated OutputFormat enum member.
Raises:
ValueError: If format is not recognized.
"""
try:
return OutputFormat(value.lower())
except ValueError:
valid_formats = [f.value for f in OutputFormat]
raise ValueError(
f"Invalid format '{value}'. "
f"Valid options: {', '.join(valid_formats)}"
)
# Usage at API boundary
def export_data(data: list[dict], format_str: str) -> bytes:
output_format = parse_output_format(format_str) # Fail fast
# Rest of function uses typed OutputFormat
...
Use Pydantic models for structured input validation with automatic error messages.
from pydantic import BaseModel, Field, field_validator
class CreateUserInput(BaseModel):
"""Input model for user creation."""
email: str = Field(..., min_length=5, max_length=255)
name: str = Field(..., min_length=1, max_length=100)
age: int = Field(ge=0, le=150)
@field_validator("email")
@classmethod
def validate_email_format(cls, v: str) -> str:
if "@" not in v or "." not in v.split("@")[-1]:
raise ValueError("Invalid email format")
return v.lower()
@field_validator("name")
@classmethod
def normalize_name(cls, v: str) -> str:
return v.strip().title()
# Usage
try:
user_input = CreateUserInput(
email="user@example.com",
name="john doe",
age=25,
)
except ValidationError as e:
# Pydantic provides detailed error information
print(e.errors())
Use Python's built-in exception types appropriately, adding context as needed.
| Failure Type | Exception | Example |
|---|---|---|
| Invalid input | ValueError |
Bad parameter values |
| Wrong type | TypeError |
Expected string, got int |
| Missing item | KeyError |
Dict key not found |
| Operational failure | RuntimeError |
Service unavailable |
| Timeout | TimeoutError |
Operation took too long |
| File not found | FileNotFoundError |
Path doesn't exist |
| Permission denied | PermissionError |
Access forbidden |
# Good: Specific exception with context
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Avoid: Generic exception, no context
raise Exception("Invalid parameter")
Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.
ValueError, TypeError, not generic Exceptionraise ... from e to preserve debug infoReproducido de wshobson/agents bajo licencia MIT. Leer esta página en markdown.
2 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.
Este repo incluye 180 skills. Si instalas uno, normalmente ya tienes los demás.
Úsalo al seleccionar y colocar iconos, imágenes, SVGs, diagramas o infografías de apoyo aprobados en un PPTX editable.
Úsalo cuando pidan optimizar un prompt, mejorar su rendimiento, diseñar una plantilla, aplicar chain-of-thought, few-shot prompting o técnicas avanzadas de prompt engineering para producción.
Úsalo al redactar o reparar una especificación JSON con coordenadas explícitas para un PPTX editable.
Úsalo para validar o reparar un PPTX editable en cuanto a geometría, accesibilidad, editabilidad nativa, linaje de fuente e integridad del paquete OOXML.
Úsalo para analizar un PPTX de referencia en modo solo lectura: estructura, tema, tipografía, ritmo de layout, diagnósticos, catálogos de plantillas derivados o inspección segura del paquete OOXML.
Úsalo al preparar la narrativa, las fuentes y el contexto de diseño para un nuevo deck PPTX editable.
Domina el sistema de tipos avanzado de TypeScript: generics, tipos condicionales, mapped types, template literals y utility types para aplicaciones type-safe.
Patrones de resiliencia en Python: reintentos automáticos, backoff exponencial, timeouts y decoradores tolerantes a fallos para servicios.
Organización de proyectos Python, arquitectura de módulos y diseño de APIs públicas con __all__, para nuevos proyectos o reorganización de directorios.