Skip to content

Type Hints

Python

Add static type checking with type hints and mypy.

Official Site
01

Overview

Type hints annotate function signatures and variables. Optional runtime behavior (not enforced). Use mypy/pyright for static checking. Types: int, str, List[int], Dict[str,int], Optional[T], Union[A,B], Callable. Generic types with TypeVar.

bash
from typing import List, Dict, Optional

def greet(name: str) -> str:
    return f"Hello {name}"

def find(items: List[int], target: int) -> Optional[int]:
    return next((i for i,v in enumerate(items) if v==target), None)

# Python 3.9+: list[int], dict[str,int]
# Python 3.10+: int | str instead of Union
02

Best Practices

Use mypy or pyright for checking. Start with function signatures. Use Optional[T] for nullable. Use TypedDict for dict shapes. Use Protocol for structural typing. Python 3.9+ allows list[int] instead of List[int]. gradual typing: annotate new code.)

Ready to try Type Hints?

Visit the official site for the latest version and full documentation.

Visit Type Hints