Lesson 28 of 52Pythonic Python
Type Hints
Annotate Python code with modern type hints, catch bugs with mypy or pyright, and know what hints do not do.
Open any modern Python codebase, FastAPI app or library and you will see def get_user(user_id: int) -> User | None:. Type hints document what a function expects and returns, let your editor autocomplete and flag mistakes as you type, and let tools like mypy and pyright catch whole classes of bugs before the code runs. FastAPI and Pydantic even use them to validate requests. Most teams now require them.
Annotating variables and functions
A type hint (or annotation) is written after a colon for parameters and variables, and after -> for a return value.
Press Run (⌘ Enter) to see what happens.Hints are stored on the function (__annotations__) but Python itself does nothing else with them. That surprises everyone the first time:
What does this print?
def double(n: int) -> int:
return n * 2
print(double("ab"))The real value of hints comes from static tools that read your code without running it.
Collections, None and unions
Since Python 3.9 you write generic collections with the built-in types and square brackets. Since 3.10, X | Y means "either type".
scores: list[int] = [90, 85]
lookup: dict[str, float] = {"pi": 3.14}
point: tuple[int, int] = (3, 4) # exactly two ints
history: tuple[str, ...] = ("a", "b") # any length
unique: set[str] = set()
def find(user_id: int) -> str | None: # may return nothing
...
def parse(value: int | str) -> int: # accepts either
...str | None is the modern spelling of Optional[str] from the typing module. You will see both. "Optional" means "may be None", not "the argument is optional".
A checker forces you to handle the None case before using the value. This is called narrowing:
Press Run (⌘ Enter) to see what happens.def f(x: Optional[int]) mean?Literal, TypedDict and Callable
The typing module covers more precise shapes:
from typing import Literal, TypedDict
from collections.abc import Callable
Mode = Literal["r", "w", "a"] # only these exact values
def open_log(mode: Mode) -> None: ...
class UserDict(TypedDict): # a dict with known keys
id: int
email: str
admin: bool
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
return fn(a, b) # fn takes two ints, returns an intLiteralrestricts a value to specific constants. Great for modes and status strings.TypedDictdescribes a dict with fixed keys, such as parsed JSON, where a dataclass would be overkill.Callable[[args], return]describes a function you pass in. Import it fromcollections.abc.
Match each hint to what it means.
Functions that return nothing, never return, or yield
Three kinds of function trip people up the first time they annotate them.
Returning nothing. A function that only has side effects returns None, so annotate it -> None. Do not leave the return type off: to mypy an unannotated return means "not checked", not "returns nothing". And avoid functions that return a value on some paths and fall off the end on others. The checker will force every caller to handle None, which is usually the checker telling you the function has two jobs.
Never returning. A function that always raises or exits, like fail(message) that raises an HTTPException, gets -> Never (from typing, 3.11; older code spells it NoReturn). The checker then knows code after the call is unreachable, so narrowing keeps working:
from typing import Never
def fail(message: str) -> Never:
raise ValueError(message)
def port(raw: str | None) -> int:
if raw is None:
fail("PORT is not set")
return int(raw) # the checker knows raw is a str hereYielding. A generator function does not return its items, it returns a generator object, and the hint describes that object. For the common case, use Iterator[T]: "something you can loop over that produces T". When the generator also receives values with send() or returns a final value, use Generator[YieldType, SendType, ReturnType]. Since Python 3.13 the last two default to None, so Generator[int] is valid too.
Press Run (⌘ Enter) to see what happens.A @contextmanager function is a generator too, so it is annotated -> Iterator[Connection], where Connection is whatever it yields. Async versions use AsyncIterator[T] and AsyncGenerator[T].
For callbacks, Callable[[Event], None] documents that you ignore the result. If you genuinely accept callbacks that return anything, Callable[[Event], object] says so explicitly.
Generics: TypeVar and the 3.12 syntax
What is the return type of a function that returns the first item of a list? It depends on the list: list[int] gives int, list[str] gives str. A type variable expresses "the same type, whatever it is".
def first[T](items: list[T]) -> T:
return items[0]
class Box[T]:
def __init__(self, value: T) -> None:
self.value = valuefrom typing import TypeVar, Generic
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = valuePress Run (⌘ Enter) to see what happens.Without the type variable you would write list[object] -> object, and the checker would complain about n + 1. Generics keep the precise type flowing through your function. The new def f[T] syntax (PEP 695) is the one to use in new code.
Type aliases with type
Long types get repeated: dict[str, list[tuple[int, str]]] in five signatures is unreadable and a pain to change. A type alias gives it a name. Since Python 3.12 the type statement is the way to write one:
Press Run (⌘ Enter) to see what happens.What the type statement gives you over the old UserId = int or UserId: TypeAlias = int:
- It is lazy. The right-hand side is only evaluated when something asks for
__value__. That is whyJsoncan refer to itself, and why an alias can mention a class defined further down the file, with no quotes. - It can be generic.
Pair[T]takes a type parameter, just likedef swap[T]. - It is unambiguous. A plain
X = intcould be an alias or just a variable that holds a class; checkers have to guess.type X = intcan only be an alias.
An alias is just another name for the same type. UserId and int are fully interchangeable, so the checker will happily let you pass an OrderId where a UserId is expected. When you want the checker to keep two kinds of id apart, use NewType, which Typing Patterns for Real Code covers. And because the alias object is not a class, isinstance(x, UserId) raises TypeError: at runtime, check against the real type.
What does this print?
type Celsius = float def warm(t: Celsius) -> bool: return t > 20 print(warm(25), Celsius.__value__)
Protocol: typing by shape
You met Protocol in the inheritance lesson. In type hints it says "any object with these methods", which keeps your functions flexible:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def close_all(things: list[SupportsClose]) -> None:
for t in things:
t.close()Files, sockets and your own classes all fit, with no shared base class needed.
Accept abstract, return concrete
Here is a signature you will see in code review:
def normalise(emails: list[str]) -> list[str]: ...It works, but it is stricter than it needs to be. The function only loops over emails, so it could just as well take a tuple, a set, a generator or a dict's keys. With list[str] the checker rejects all of those, and callers start writing normalise(list(emails)) everywhere. The rule seniors follow: parameters should ask for the least they need, return types should promise the most you can deliver.
Press Run (⌘ Enter) to see what happens.Iterable accepts lists, tuples, sets, dict views, files and generators. Use it when you make one pass.
The same idea applies to dicts: take Mapping[str, int] when you only read, MutableMapping or dict when you write. There is a second, subtler win. Sequence and Mapping are read-only, which lets the checker accept a list[int] where a Sequence[float] is expected. A list[float] parameter would reject it, because the function could append a float to the caller's list of ints. Generics and Protocols in Depth explains this (it is called variance) properly.
Do not over-apply it to returns. Returning Iterable[str] "to stay flexible" means every caller who needs len() must wrap your result in list(). If you want freedom to change the implementation later, Sequence[str] is a reasonable middle ground for a read-only result.
def total(prices: ...) -> float only does return sum(prices). Which parameter type is the best choice?Any, object, or no annotation at all
Three ways to say "I am not being specific" behave very differently:
object: any value is accepted, but you can do almost nothing with it until you narrow it withisinstance. Safe.Any: any value is accepted, and you can do anything with it.x.whatever()passes. Checking is switched off for that value and everything derived from it.- No annotation: the parameter is treated as
Any. Worse, mypy by default does not type-check the body of a function with no annotations at all, so obvious errors inside it are silently skipped. Pyright checks the body but has to guess the parameter types. Adding even one annotation (such as-> None) makes mypy check the whole function.
That last point is why a half-annotated codebase can feel safe when it is not. mypy's --strict mode turns on disallow_untyped_defs so unannotated functions become errors, and check_untyped_defs is a gentler step that at least checks their bodies. Generics and Protocols in Depth goes further into object versus Any and how Any spreads.
def describe(value: object) -> str: return value.upper(). What does a type checker say?Running a type checker
Hints pay off when a tool checks them. The two main ones are mypy (the original) and pyright (fast, and powers VS Code's Pylance). Both run without executing your code:
uv add --dev mypyuv run mypy src/src/app.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]
Found 1 error in 1 file (checked 3 source files)Start with hints on function signatures (parameters and returns); checkers infer most local variables. Turn on strict = true in your config once a project is fully annotated. And remember that hints describe your own code. Data from outside (JSON, forms, env vars) still needs runtime validation, which is exactly what Pydantic adds.
A generic group_by
Write a generic function group_by(items, key) that groups items by the result of calling key(item).
- Return a
dictmapping each key to the list of items with that key, in their original order. - Keys appear in the order they are first seen.
- Annotate it with type variables using the Python 3.12 syntax:
def group_by[T, K](items: list[T], key: Callable[[T], K]) -> dict[K, list[T]].
group_by(["apple", "avocado", "banana"], lambda w: w[0])
# {"a": ["apple", "avocado"], "b": ["banana"]}
group_by([1, 2, 3, 4], lambda n: n % 2 == 0)
# {False: [1, 3], True: [2, 4]}Validate at the boundary
Type hints are not checked at runtime, so data from outside (like parsed JSON) must be validated by hand (or by Pydantic). Write validate_user(raw) that turns an untrusted dict into a User (a TypedDict with keys id: int, email: str, admin: bool).
Rules:
idis required and must be anint. Note thatTrueis technically anintin Python; reject booleans.emailis required and must be astrcontaining"@".adminis optional, defaults toFalse, and must be aboolif present.- Unknown keys are dropped.
- Raise
TypeErrorfor a missing key or wrong type, andValueErrorfor an email without"@".
validate_user({"id": 7, "email": "ada@example.com", "extra": 1})
# {"id": 7, "email": "ada@example.com", "admin": False}
validate_user({"id": "7", "email": "a@b.c"}) # TypeError
validate_user({"id": 7, "email": "nope"}) # ValueError- type hint
- An annotation like
x: intor-> strthat documents a type for tools. Not enforced at runtime. - X | None
- A union meaning the value may be
None; identical toOptional[X]. - narrowing
- A checker learns a more specific type after a check like
if x is None: return. - TypedDict
- Describes a dict with a fixed set of keys and value types.
- type variable
- A placeholder type (
T) that links input and output types, writtendef f[T](...)in 3.12+. - mypy / pyright
- Static type checkers that read hints and report type errors without running code.