Type Hints
Type Hints
Section titled “Type Hints”Python is dynamically typed, but type hints (PEP 484+) let you annotate variables and functions for better tooling, readability, and static analysis.
Basic Annotations
Section titled “Basic Annotations”name: str = "Alice"age: int = 30price: float = 9.99active: bool = TrueFunction Annotations
Section titled “Function Annotations”def greet(name: str) -> str: return f"Hello, {name}!"
def add(a: int, b: int) -> int: return a + b
def process(data: list) -> None: for item in data: print(item)typing Module (Python 3.5–3.8)
Section titled “typing Module (Python 3.5–3.8)”from typing import List, Dict, Tuple, Set, Optional, Union, Any, Callable
def get_names() -> List[str]: return ["Alice", "Bob"]
def get_scores() -> Dict[str, int]: return {"Alice": 90}
def get_point() -> Tuple[int, int]: return (1, 2)
def find_user(id: int) -> Optional[str]: # str or None return None
def parse(value: Union[int, str]) -> str: return str(value)Built-in Generics (Python 3.9+)
Section titled “Built-in Generics (Python 3.9+)”No need to import from typing for common types:
def get_names() -> list[str]: return ["Alice", "Bob"]
def get_scores() -> dict[str, int]: return {"Alice": 90}
def get_point() -> tuple[int, int]: return (1, 2)Optional and | Union (Python 3.10+)
Section titled “Optional and | Union (Python 3.10+)”# Old stylefrom typing import Optionaldef find(id: int) -> Optional[str]: ...
# New style (Python 3.10+)def find(id: int) -> str | None: ...
def parse(value: int | str) -> str: ...TypeVar and Generics
Section titled “TypeVar and Generics”from typing import TypeVar, Generic
T = TypeVar('T')
def first(items: list[T]) -> T: return items[0]
class Stack(Generic[T]): def __init__(self) -> None: self._items: list[T] = []
def push(self, item: T) -> None: self._items.append(item)
def pop(self) -> T: return self._items.pop()Callable
Section titled “Callable”from typing import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int: return func(a, b)
apply(lambda x, y: x + y, 3, 4) # 7TypedDict
Section titled “TypedDict”from typing import TypedDict
class User(TypedDict): name: str age: int email: str
user: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}dataclass with Type Hints
Section titled “dataclass with Type Hints”from dataclasses import dataclass
@dataclassclass Point: x: float y: float label: str = "origin"
p = Point(1.0, 2.0)print(p) # Point(x=1.0, y=2.0, label='origin')Final and Literal
Section titled “Final and Literal”from typing import Final, Literal
MAX_SIZE: Final = 100 # cannot be reassigned
Direction = Literal["north", "south", "east", "west"]
def move(direction: Direction) -> None: print(f"Moving {direction}")Runtime Type Checking
Section titled “Runtime Type Checking”Type hints are not enforced at runtime by default. Use libraries like:
mypy— static type checkerpyright— Microsoft’s type checker (used in Pylance/VS Code)pydantic— runtime validation
pip install mypymypy my_script.py