Type Hints — Python

A type hint is a note in the code that names the expected type: param: type on a parameter, -> type before the colon at the end of def, and name: type = value…

The jars in Mr. Darto's kitchen are labelled "SUGAR" and "SALT". A label says what should be inside. But the jar does not refuse when someone puts salt into the sugar jar. Only an inspector, who compares each label with what is inside the jar before the stall opens, finds that mistake.

A type hint works like the label on those jars, but for code. It is a note that names the type of a parameter, a return value or a variable, for example "this total is an int". Like the jar, Python does not refuse a wrong value: it still runs the code as it is. The inspector who reads the labels is a tool (a helper program) such as mypy.

Writing a type hint

The function and the variable below have type hints:

def discount(total: int) -> int:
    if total >= 100:
        return 15
    elif total >= 50:
        return 10
    elif total >= 25:
        return 5
    else:
        return 0

today: int = 89
print(discount(today))   # 10

Hints are not enforced while the program runs

The function below asks for two ints, but the call gives it the string "15". Before you look at the result, guess: does Python stop with an error, or does it print something?

def total_price(price: int, quantity: int) -> int:
    return price * quantity

print(total_price("15", 3))

This is the result:

$ python3 stall.py
151515

Python prints something, with no error. Python reads the hints and keeps them, but does not check them: a value of another type is still accepted. (You can see the stored hints in total_price.__annotations__, which holds {'price': <class 'int'>, 'quantity': <class 'int'>, 'return': <class 'int'>}.) A string times 3 means the string is repeated three times. So the result is the text "15" three times in a row, not 45. The program runs with no error, and the number is wrong without any warning.

Replace "15" with None, and only then is there an error. Even that error comes from the * operation on line 2, not from the hint:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 4, in <module>
    print(total_price(None, 3))
          ~~~~~~~~~~~^^^^^^^^^
  File "/home/darto/stall.py", line 2, in total_price
    return price * quantity
           ~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

mypy: the checker that reads hints

mypy reads your code without running it, then checks whether every value matches its hint. Install it once inside a virtual environment (a .venv folder that holds your project's packages, explained in the lesson Modules & Imports):

  1. Create the folder: python3 -m venv .venv
  2. Activate it: source .venv/bin/activate (on Windows .venv\Scripts\activate)
  3. Install mypy: pip install mypy

Without a virtual environment, the Python from Homebrew and from recent Ubuntu or Debian refuses pip install with error: externally-managed-environment. Other options: pipx install mypy or uv tool install mypy. Both set up a virtual environment for mypy by themselves, so you don't need to make one. Once it is installed, run it in the terminal:

$ mypy stall.py
stall.py:4: error: Argument 1 to "total_price" has incompatible type "str"; expected "int"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Types for lists and dicts

A hint can also name the type of what is inside a list or a dictionary:

def best_sellers(sales: dict[str, int], minimum: int = 3) -> list[str]:
    return [item for item, count in sales.items() if count >= minimum]

sales = {"coffee with milk": 3, "sweet tea": 4, "toast": 2}
print(best_sellers(sales))      # ['coffee with milk', 'sweet tea']
print(best_sellers(sales, 2))   # ['coffee with milk', 'sweet tea', 'toast']

This lesson's exercise uses the same pattern for exam scores: filter_passed(scores: list[int], limit: int = 70) -> list[int].

The order on the def line is always: def name(param: type) -> return_type:. The -> and the return type come before the colon. Python refuses the two forms below with SyntaxError: invalid syntax:

Allowed to be empty: X | None

The function below uses menu.get(name), which returns None when the item is not on the menu. So the function's result can be an int, or it can be None. Its hint is int | None, meaning "an int, or None":

def find_price(menu: dict[str, int], name: str) -> int | None:
    return menu.get(name)

menu = {"coffee with milk": 15, "sweet tea": 5}
price = find_price(menu, "iced tea")
print(price + 1)

In that code "iced tea" is not on the menu, so None comes back, and None cannot be added to a number. Python only stops when the program runs, with TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. mypy finds the problem before the program runs:

$ mypy stall.py
stall.py:6: error: Unsupported operand types for + ("None" and "int")  [operator]
stall.py:6: note: Left operand is of type "int | None"
Found 1 error in 1 file (checked 1 source file)

mypy says: the value on the left of the plus sign has the type int | None, so it may be None. To fix it, check first with if price is None: (is None checks whether the value is None), then do the addition in the else part. After that mypy answers Success.

⚠️ Hints mistaken for guards, and syntax that isn't Python

TL;DR: A type hint is a note in the code that names the expected type: param: type on a parameter, -> type before the colon at the end of def, and name: type = value on a variable. Python does not enforce hints while the program runs (it does not check the types): total_price("15", 3) with int hints still runs and prints 151515. Tools (helper programs) such as mypy read the hints without running the code, then report incompatible type (the type does not match) before the program runs. mypy does not check a function with no hints. A hint for a collection (list, dict, tuple, set) names the type of its items in square brackets, with no import: list[int], dict[str, int], tuple[str, int], set[str]. A value that may be empty (None) is written int | None, the same as Optional[int]. A def line is always written like def average(n: list[int]) -> float:. list<int> is not Python.

⚡ A type label

Write:

def discount(total: int) -> int:
    if total >= 100:
        return 15
    elif total >= 50:
        return 10
    elif total >= 25:
        return 5
    else:
        return 0

today: int = 89
print(discount(today))   # 10

Meaning: The type notes in this code are called type hints. total: int means the parameter total should be an int. -> int before the colon at the end of the def line names the type of the function's return value. today: int = 89 gives a variable a hint.

⚡ Hints aren't enforced

Write:

def total_price(price: int, quantity: int) -> int:
    return price * quantity

print(total_price("15", 3))
Guess first: the hints say int, but the call sends a string. Does Python stop with an error, or print something?

It prints 151515, with no error. The text "15" is repeated three times, and the number is wrong without any warning.

Meaning: Python stores hints, but doesn't check them while the program runs. Hints are only guidance for code editors and checking programs.

⚡ mypy reads the labels

Meaning: mypy is a program that checks hints. It reads your code without running it. For the code in the step before this one, mypy reports has incompatible type "str"; expected "int" on line 4, before the program runs. mypy doesn't check a function with no hints at all.

⚡ Collections and empty values

Guess first: a hint for a list of ints is written list<int>, like in the Java language. Does Python accept it?

No. Python stops with SyntaxError: invalid syntax. In Python, a list of ints is written list[int].

Meaning: A hint for a collection such as a list or a dict names the type of its items in square brackets, with no import: list[int], dict[str, int] (string keys, int values). A value that can be None is written int | None.

What you will learn