Learn / Intermediate / Lesson 8

Type hints

11 min Tested on Python 3.15Updated By
In short

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

Python
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__)
Output
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

Python
def double(x: int) -> int:
    return x * 2

print(double("ha"))   # runs fine — Python ignores hints at runtime
Output
haha

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

Python
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"))
Output
No such user
7 7.5

Aliases, TypedDict and Literal

Python
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))
Output
Arrival (2016) — published
2
  • type Name = ... (Python 3.12+) gives a long type a short name.
  • TypedDict describes the keys of a dictionary, e.g. JSON from an API.
  • Literal limits a value to a few exact options.

Generic functions

Python
def first[T](items: list[T]) -> T:
    return items[0]

print(first([3, 1, 2]))
print(first(["x", "y"]))
Output
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

terminal
$ 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 [].

Expected output:
6.17
None
Your code

Quick check

1. Does Python raise an error when a hinted function gets the wrong type?

2. How do you write "a string or nothing"?

3. Which is the modern way to hint a list of integers?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →