# Variable annotations
name: str = 'Alice'
age: int = 25
height: float = 5.9
is_active: bool = True
# These are ANNOTATIONS — Python doesn't enforce them!
name: str = 123 # No error at runtime!def greet(name: str) -> str:
return f'Hello, {name}'
def add(a: int, b: int) -> int:
return a + b
def process(items: list, threshold: float) -> bool:
return any(x > threshold for x in items)
# None return type for side-effect functions
def log(message: str) -> None:
print(f'[LOG] {message}')from typing import List, Dict, Tuple, Set, Optional
# List of strings
def get_names() -> List[str]:
return ['Alice', 'Bob']
# Dict with string keys and int values
def word_count(text: str) -> Dict[str, int]:
return {w: text.count(w) for w in set(text.split())}
# Tuple with specific types
def get_bounds() -> Tuple[float, float]:
return (0.0, 100.0)
# Optional — can be None
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return 'Alice'
return None # Valid!from typing import Union, Literal
# Multiple possible types
def process_id(id_val: Union[int, str]) -> str:
return str(id_val)
# Python 3.10+ syntax
def process_id(id_val: int | str) -> str:
return str(id_val)
# Exact values
def set_mode(mode: Literal['dev', 'prod', 'test']) -> None:
print(f'Mode: {mode}')
# set_mode('staging') # mypy would catch this!from typing import Dict, List, Tuple
# Complex type given a readable name
UserData = Dict[str, Union[str, int, List[str]]]
Coordinate = Tuple[float, float]
Matrix = List[List[float]]
def process_user(data: UserData) -> None:
pass
def distance(p1: Coordinate, p2: Coordinate) -> float:
return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) ** 0.5# Install: pip install mypy
# Run: mypy script.py
# script.py:
def add(a: int, b: int) -> int:
return a + b
add('hello', 'world') # mypy: error: Argument 1 has incompatible type "str"Create a function `analyze_data(numbers: List[int]) -> Dict[str, Union[int, float, List[int]]]` that returns a dict with keys: 'count' (int), 'mean' (float), 'max' (int), 'min' (int), 'above_mean' (List[int]). Create type aliases `NumberList` and `AnalysisResult`. Create a function `search(items: List[str], query: str) -> Optional[int]` that returns the index or None. Add proper type hints to everything.