Type hints and static checking
Describe the types you expect and let a checker find mistakes before you run the code.
Type hints annotate what a function accepts and returns. Python does not enforce them at run time. Tools such as mypy and pyright, and your editor, use them to find bugs early.
def total(prices: list[float], tax: float = 0.21) -> float:
return sum(prices) * (1 + tax)
def find(users: dict[int, str], uid: int) -> str | None:
return users.get(uid)- Built-in generics:
list[int],dict[str, int],tuple[int, ...]. X | Nonemarks a value that can be missing (older code writesOptional[X]).Callable[[int], str]describes a function.Iterable[T]accepts any iterable.
Why it helps
name = find(users, 3)
print(name.upper()) # checker: "None" has no attribute "upper"The checker sees that find can return None and warns you to handle it. That mistake would otherwise be a crash in production.
Typed data structures
from typing import TypedDict, Protocol
class User(TypedDict):
id: int
name: str
class Closeable(Protocol):
def close(self) -> None: ...A Protocol describes behaviour: any object with a close() method fits, with no inheritance needed (structural typing).
NoteAdd types gradually, starting with the public functions. Run mypy . in your tests or CI so the hints stay true.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.