Skip to content

Advanced Typing: Static Type Hints

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

  1. Type Annotations - Syntax and semantics
  2. Type Checking - mypy, pyright tools
  3. Generic Types - List[T], Dict[K, V], TypeVar
  4. Protocols - Structural subtyping
  5. 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.
    ...