Type hints (PEP 484+) are optional annotations that declare expected types for parameters, returns, and variables. Python does not enforce them at runtime by default; tools like mypy, pyright, and IDEs use them for static checking and better autocomplete.
from typing import Iterable, Optional
def normalize_name(name: str) -> str:
return name.strip().title()
def find_user(user_id: int) -> Optional[dict[str, str]]:
if user_id <= 0:
return None
return {"id": str(user_id), "name": "Asha"}
def mean(nums: Iterable[float]) -> float:
values = list(nums)
return sum(values) / len(values)
# Python 3.10+ union syntax
def parse(flag: str | None) -> bool:
return bool(flag)Benefits
- Catch mismatches before production.
- Document APIs without long prose.
- Enable safer refactors.
Limits
- Not a substitute for tests or runtime validation (use
pydantic/ explicit checks when needed). - Dynamic patterns may need
Protocol,TypeVar, orAnycarefully.
Interview line: "Type hints are for humans and static analyzers; CPython ignores them unless you opt into runtime use."