Type hints
Type hints describe what types a variable, parameter or return value should have, like def total(prices: list[float]) -> float:. Python doesn't enforce them while running; instead your editor, type checkers such as mypy, and AI coding assistants use them to catch mistakes early and understand your code.
The basics
def total(prices: list[float], discount: float = 0.0) -> float:
return round(sum(prices) * (1 - discount), 2)
city: str = "Ghent"
scores: dict[str, int] = {"ana": 91, "ben": 78}
location: tuple[float, float] = (51.05, 3.72)
print(total([10.0, 20.5], discount=0.1))
print(total.__annotations__)27.45
{'prices': list[float], 'discount': <class 'float'>, 'return': <class 'float'>}Use the built-in names directly: list[int], dict[str, float], tuple[int, ...], set[str]. Older code imports List and Dict from typing — that's no longer needed.
Hints don't stop wrong values
def double(x: int) -> int:
return x * 2
print(double("ha")) # runs fine — Python ignores hints at runtimehaha
A type checker would flag that call before you run it. That's the point: hints move bugs from production to your editor.
Optional values and unions
def find_user(user_id: int) -> str | None:
users = {1: "Ana", 2: "Ben"}
return users.get(user_id)
def parse(value: str) -> int | float:
return float(value) if "." in value else int(value)
name = find_user(3)
if name is None:
print("No such user")
print(parse("7"), parse("7.5"))No such user 7 7.5
Aliases, TypedDict and Literal
from typing import Literal, TypedDict
type Matrix = list[list[float]]
class Movie(TypedDict):
title: str
year: int
Status = Literal["draft", "published"]
def describe(movie: Movie, status: Status) -> str:
return f"{movie['title']} ({movie['year']}) — {status}"
identity: Matrix = [[1, 0], [0, 1]]
print(describe({"title": "Arrival", "year": 2016}, "published"))
print(len(identity))Arrival (2016) — published 2
type Name = ...(Python 3.12+) gives a long type a short name.TypedDictdescribes the keys of a dictionary, e.g. JSON from an API.Literallimits a value to a few exact options.
Generic functions
def first[T](items: list[T]) -> T:
return items[0]
print(first([3, 1, 2]))
print(first(["x", "y"]))3 x
[T] after the name (Python 3.12+) says "whatever type goes in, the same type comes out", so the checker knows first([3, 1, 2]) is an int.
Checking your code
$ uv add --dev mypy
$ uv run mypy app.py
app.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)Popular checkers are mypy and Pyright (built into VS Code's Pylance). Start by adding hints to function signatures; you rarely need them on local variables.
Practice
Write a fully type-hinted function average(values: list[float]) -> float | None that returns None for an empty list and the rounded (2 decimals) average otherwise. Print the result for [4.0, 5.5, 9.0] and for [].
6.17 None