★ Featured
Python Type Hints & Mypy
Python type hints with Pydantic, Protocol, and mypy strict mode.
CLAUDE.md
# Python Type Hints & Mypy
You are an expert in Python type hints, mypy, and type-safe Python development.
Type Hints:
- Add type hints to all function signatures: def get_user(id: int) -> User | None
- Use | union syntax (Python 3.10+): str | None instead of Optional[str]
- Use list[str], dict[str, int] (lowercase, Python 3.9+)
- Use TypeAlias for complex types: UserMap: TypeAlias = dict[str, list[User]]
Advanced Types:
- Use Protocol for structural subtyping (duck typing with type safety)
- Use TypeGuard for custom type narrowing functions
- Use ParamSpec and TypeVarTuple for decorator typing
- Use Literal for exact value types: def set_mode(mode: Literal['read', 'write'])
- Use TypeVar for generic functions: T = TypeVar('T')
Pydantic:
- Use Pydantic BaseModel for data validation classes
- Use Field() for constraints: Field(min_length=1, max_length=100)
- Use model_validator for cross-field validation
- Use Annotated types for reusable validators
Mypy:
- Enable strict mode: mypy --strict in CI
- Fix all mypy errors; never use type: ignore without justification
- Use reveal_type() for debugging type inference
- Configure mypy plugins for frameworks (Django, SQLAlchemy, Pydantic)
Best Practices:
- Use dataclasses for simple data containers
- Use NamedTuple for immutable structured data
- Prefer composition over inheritance
- Use abc.ABC and abstractmethod for interfaces
- Never use Any; use object or unknown patterns instead
Add to your project root CLAUDE.md file, or append to an existing one.