# Python Type Safety > Seguridad de tipos en Python con anotaciones, genéricos, protocolos y verificación estricta con mypy/pyright. Fuente: https://skillsagentes.com/skills/wshobson/agents/python-type-safety Markdown: https://skillsagentes.com/skills/wshobson/agents/python-type-safety.md Repositorio: https://github.com/wshobson/agents Autor: wshobson Licencia: MIT Actualizado: hace 4 meses Coste de contexto: 52 tok instalada, 1.4k tok al activarse, 2.9k tok con todos los archivos del bundle Bundle: 2 archivos, 11 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add wshobson/agents --skill python-type-safety --agent claude-code # Cursor npx -y skills add wshobson/agents --skill python-type-safety --agent cursor # Codex npx -y skills add wshobson/agents --skill python-type-safety --agent codex # Gemini CLI npx -y skills add wshobson/agents --skill python-type-safety --agent gemini # Windsurf npx -y skills add wshobson/agents --skill python-type-safety --agent windsurf # Cline npx -y skills add wshobson/agents --skill python-type-safety --agent cline ``` ## Qué hace - Añade anotaciones de tipos a firmas públicas, funciones y clases - Aplica sintaxis moderna de uniones (T | None) en vez de Optional[T] - Implementa clases genéricas con TypeVar y Generic para preservar tipos - Define protocolos para interfaces estructurales sin herencia - Usa guardas de tipo para el estrechamiento (narrowing) dentro del código ## Cuándo usarla - Al añadir anotaciones de tipo a código existente - Al crear clases genéricas y reutilizables - Al definir interfaces estructurales con protocolos - Al configurar mypy o pyright para verificación estricta ## Qué la activa - "Añade anotaciones de tipo a este módulo de Python" - "Crea una clase genérica Result[T, E] type-safe" - "Configura mypy --strict para este proyecto" - "Define un Protocol para esta interfaz sin usar herencia" ## Antes de instalar - Requiere Python 3.10+ para la sintaxis de uniones moderna (T | None), y mypy o pyright para la verificación estática. ## Archivos - SKILL.md — 6 KB - references/details.md — 6 KB ## SKILL.md Reproducido tal cual desde wshobson/agents bajo MIT. Esta sección es el documento original y está en inglés. # Python Type Safety Leverage Python's type system to catch errors at static analysis time. Type annotations serve as enforced documentation that tooling validates automatically. ## When to Use This Skill - Adding type hints to existing code - Creating generic, reusable classes - Defining structural interfaces with protocols - Configuring mypy or pyright for strict checking - Understanding type narrowing and guards - Building type-safe APIs and libraries ## Core Concepts ### 1. Type Annotations Declare expected types for function parameters, return values, and variables. ### 2. Generics Write reusable code that preserves type information across different types. ### 3. Protocols Define structural interfaces without inheritance (duck typing with type safety). ### 4. Type Narrowing Use guards and conditionals to narrow types within code blocks. ## Quick Start ```python def get_user(user_id: str) -> User | None: """Return type makes 'might not exist' explicit.""" ... # Type checker enforces handling None case user = get_user("123") if user is None: raise UserNotFoundError("123") print(user.name) # Type checker knows user is User here ``` ## Fundamental Patterns ### Pattern 1: Annotate All Public Signatures Every public function, method, and class should have type annotations. ```python def get_user(user_id: str) -> User: """Retrieve user by ID.""" ... def process_batch( items: list[Item], max_workers: int = 4, ) -> BatchResult[ProcessedItem]: """Process items concurrently.""" ... class UserRepository: def __init__(self, db: Database) -> None: self._db = db async def find_by_id(self, user_id: str) -> User | None: """Return User if found, None otherwise.""" ... async def find_by_email(self, email: str) -> User | None: ... async def save(self, user: User) -> User: """Save and return user with generated ID.""" ... ``` Use `mypy --strict` or `pyright` in CI to catch type errors early. For existing projects, enable strict mode incrementally using per-module overrides. ### Pattern 2: Use Modern Union Syntax Python 3.10+ provides cleaner union syntax. ```python # Preferred (3.10+) def find_user(user_id: str) -> User | None: ... def parse_value(v: str) -> int | float | str: ... # Older style (still valid, needed for 3.9) from typing import Optional, Union def find_user(user_id: str) -> Optional[User]: ... ``` ### Pattern 3: Type Narrowing with Guards Use conditionals to narrow types for the type checker. ```python def process_user(user_id: str) -> UserData: user = find_user(user_id) if user is None: raise UserNotFoundError(f"User {user_id} not found") # Type checker knows user is User here, not User | None return UserData( name=user.name, email=user.email, ) def process_items(items: list[Item | None]) -> list[ProcessedItem]: # Filter and narrow types valid_items = [item for item in items if item is not None] # valid_items is now list[Item] return [process(item) for item in valid_items] ``` ### Pattern 4: Generic Classes Create type-safe reusable containers. ```python from typing import TypeVar, Generic T = TypeVar("T") E = TypeVar("E", bound=Exception) class Result(Generic[T, E]): """Represents either a success value or an error.""" def __init__( self, value: T | None = None, error: E | None = None, ) -> None: if (value is None) == (error is None): raise ValueError("Exactly one of value or error must be set") self._value = value self._error = error @property def is_success(self) -> bool: return self._error is None @property def is_failure(self) -> bool: return self._error is not None def unwrap(self) -> T: """Get value or raise the error.""" if self._error is not None: raise self._error return self._value # type: ignore[return-value] def unwrap_or(self, default: T) -> T: """Get value or return default.""" if self._error is not None: return default return self._value # type: ignore[return-value] # Usage preserves types def parse_config(path: str) -> Result[Config, ConfigError]: try: return Result(value=Config.from_file(path)) except ConfigError as e: return Result(error=e) result = parse_config("config.yaml") if result.is_success: config = result.unwrap() # Type: Config ``` ## Detailed worked examples and patterns Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient. ## Best Practices Summary 1. **Annotate all public APIs** - Functions, methods, class attributes 2. **Use `T | None`** - Modern union syntax over `Optional[T]` 3. **Run strict type checking** - `mypy --strict` in CI 4. **Use generics** - Preserve type info in reusable code 5. **Define protocols** - Structural typing for interfaces 6. **Narrow types** - Use guards to help the type checker 7. **Bound type vars** - Restrict generics to meaningful types 8. **Create type aliases** - Meaningful names for complex types 9. **Minimize `Any`** - Use specific types or generics. `Any` is acceptable for truly dynamic data or when interfacing with untyped third-party code 10. **Document with types** - Types are enforceable documentation ## Dónde encaja - Categoría: [Herramientas para desarrolladores](https://skillsagentes.com/categorias/herramientas-desarrollo.md) — Skills que cambian cómo tu agente escribe, revisa y despliega código. - Creador: [wshobson](https://skillsagentes.com/creators/wshobson.md) — 183 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Hermes Tweet](https://skillsagentes.com/skills/wshobson/agents/hermes-tweet.md): Instala y opera Hermes Tweet, un plugin de Hermes Agent para investigar X/Twitter, leer timelines, analizar tweets y ejecutar operaciones privadas o de cambio de estado con aprobación previa. - [Superself](https://skillsagentes.com/skills/wshobson/agents/superself.md): Úsalo cuando un proyecto guarda su estado en Superself: lee `self context` al iniciar sesión, vincula el trabajo a una work unit, reporta con evidencia y registra decisiones confirmadas. - [Grounded Vault](https://skillsagentes.com/skills/wshobson/agents/grounded-vault.md): Úsalo para mantener un almacén Markdown de conocimiento donde cada afirmación compilada se rastrea hasta una fuente inmutable y el drift se detecta con git diff sin gastar tokens. - [Postgresql Table Design](https://skillsagentes.com/skills/wshobson/agents/postgresql-table-design.md): Úsalo al diseñar o revisar un esquema específico de PostgreSQL: buenas prácticas, tipos de datos, indexación, restricciones, patrones de rendimiento y funciones avanzadas. - [Prompt Engineering Patterns](https://skillsagentes.com/skills/wshobson/agents/prompt-engineering-patterns.md): Ú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. ## Skills relacionadas - [Rust Async Patterns](https://skillsagentes.com/skills/wshobson/agents/rust-async-patterns.md): Domina la programación async en Rust con Tokio, traits async, manejo de errores y patrones concurrentes; útil al construir apps async, sistemas concurrentes o depurar código async. - [React Native Architecture](https://skillsagentes.com/skills/wshobson/agents/react-native-architecture.md): Crea apps React Native listas para producción con Expo, navegación, módulos nativos, sincronización offline y patrones multiplataforma. - [Python Resource Management](https://skillsagentes.com/skills/wshobson/agents/python-resource-management.md): Gestión de recursos en Python con context managers, patrones de limpieza y streaming: conexiones, manejadores de archivos y lógica de cleanup con estado acumulado. - [Python Configuration](https://skillsagentes.com/skills/wshobson/agents/python-configuration.md): Gestión de configuración en Python mediante variables de entorno y settings tipados. Útil al externalizar config, configurar pydantic-settings, gestionar secretos o implementar comportamiento por entorno. - [Python Code Style](https://skillsagentes.com/skills/wshobson/agents/python-code-style.md): Estilo de código Python, linting, formateo, convenciones de nombres y estándares de documentación; útil al escribir código nuevo, revisar estilo, configurar linters o escribir docstrings. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)