python-type-safety

Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.

By wshobson · 11,169 installs

npx skills add wshobson/agents --skill python-type-safety

Source repository · Upstream listing

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 Fundamental Patterns Pattern 1: Annotate All Public Signatures Every public function, method, and class should have type annotations. 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. Pattern 3: Type Narrowing with Guards Use conditionals to narrow types for the type checker. Pattern 4: Generic Classes Create type safe reusable containers. 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