Type Hints in Python
Chapter 29: Type Hints
6 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Type hints: labels on your values
A type hint like age: int or -> str is a label that says what a value should be; Python doesn't check it when the program runs, but people and tools read it.
Hints for lists, dicts, and maybe-None
Square brackets say what's inside a collection, list[int], dict[str, int], and str | None says "a string, or nothing".
Hinting functions: defaults, None, aliases and callbacks
Hint every parameter and the return value, including defaults (sugar: bool = False), None returns (-> None), type aliases and Callable for functions passed in.
Checking types yourself with isinstance
When a wrong type would do real damage, check it yourself with isinstance and raise a TypeError, since the hints alone won't stop anything.
Testing your code: assert and unittest
A test runs your code on an input whose right answer you already know and checks the answer, so a mistake shows up at once, every time you change the code.
Precise hints: generics, Protocol, TypedDict and Literal
A type variable lets a hint say "the same type comes out as went in", a Protocol says "anything with these methods", a TypedDict says "a dict with exactly these keys", and Literal says "only these exact values".