Advanced Typing¶
Overview¶
Type hints add static typing to Python:
- Type annotations: Hint expected types
- Type checking: mypy, pyright validate types
- Generics: Generic types and TypeVars
- Protocols: Structural subtyping
- Implications for ML: Type-safe model definitions
Key Topics¶
- Type Annotations - Syntax and semantics
- Type Checking - mypy, pyright tools
- Generic Types - List[T], Dict[K, V], TypeVar
- Protocols - Structural subtyping
- Type Narrowing - isinstance checks, guards
Benefits¶
| Benefit | Example |
|---|---|
| IDE autocomplete | Type hints enable it |
| Catch errors early | Static type checking |
| Self-documenting | Types show intent |
| Refactoring safety | Rename with confidence |
Tools¶
- mypy: Static type checker
- pyright: Microsoft's type checker
- pydantic: Runtime validation with types
- TypedDict: Typed dictionaries
- Literal: Literal type values
ML Example¶
from typing import List, Tuple
import torch
def train_model(
model: torch.nn.Module,
data: List[Tuple[torch.Tensor, torch.Tensor]],
epochs: int
) -> dict:
"""Train model with type hints."""
# Type checker validates: model is Module, data is list of tuples, etc.
...
-
Related Topics¶
- [01 Type System & Annotations](/05-py3/01-fundamentals/(01-type-system-annotations/) - Basic type hints
- [02 Execution Model & Compilation](/05-py3/09-bytecode-and-execution/(02-execution-model-compilation/) - Runtime introspection