Type hints annotate the types your functions and variables expect. Python doesn't enforce them at runtime — they're for humans and tools. Editors use them for autocomplete and warnings, and a type checker like mypy catches whole classes of bugs before you run the code.
Annotating functions
def greet(name: str, times: int = 1) -> str:return f"Hi {name}! " * times# Variables can be annotated toocount: int = 0names: list[str] = []
Containers & optionals
Use the built-in generics for containers, and the | union for "either type":
def totals(scores: dict[str, int]) -> list[int]:return list(scores.values())def find(users: list[dict], uid: int) -> dict | None: # dict OR None...# Older syntax you'll still see:from typing import Optional, Unionx: Optional[int] # same as int | Noney: Union[int, str] # same as int | str
Checking with mypy
Key takeaways
- 01Type hints annotate parameter, return and variable types.
- 02They are not enforced at runtime — they power editors and type checkers.
- 03Use built-in generics: list[int], dict[str, int]; use | for unions.
- 04X | None (or Optional[X]) means "X or None".
- 05Run mypy to catch type bugs statically; adopt hints gradually.
