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
total: intmeans "the parametertotalshould be anint". The hint goes after the parameter's name, separated by a colon.-> intnames the type of the function's return value. It goes before the colon at the end of thedefline. A function that returns nothing is written-> None.today: int = 89gives a variable a hint: name, colon, type, then=and the value.- The basic types for hints are the ones you already know:
int,float,str,bool. - The program above prints
10, the same as with no hints: hints do not change how the code runs.
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):
- Create the folder:
python3 -m venv .venv - Activate it:
source .venv/bin/activate(on Windows.venv\Scripts\activate) - 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)
stall.py:4points to line 4, where"15"is sent to the function. The message says the first argument is astr, but anintis expected.[arg-type]is the name of that kind of mistake.- The mistake is found before the program runs, so no wrong number is ever printed on a receipt.
- Code editors such as VS Code can use a checker like mypy, and mark the wrong line while you type.
- If you remove the hints (
def total_price(price, quantity):), mypy answersSuccess: no issues found in 1 source file, although the mistake is still there. The reason: mypy does not check a function with no hints at all. Python itself still prints151515.
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']
list[str]means a list whose items are strings.list[int]means a list whose items are ints.dict[str, int]means a dictionary with string keys and int values, like the sales in that code: item names and how many were sold.tuple[str, int]is for a tuple like("coffee with milk", 3), andset[str]is for a set of strings.- Since Python 3.9 you write a type such as
list[str]directly with square brackets, with no import. The old style has a capital L,List[int], and needsfrom typing import List. Without that import, Python stops withNameError: name 'List' is not defined. Did you mean: 'list'? - A parameter with both a hint and a default value is written
minimum: int = 3. In the second call,minimumis 2. Toast (2 sold) is included, because>=is also true for a number exactly equal to the limit.
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:
list<int>, the way other languages such as Java or TypeScript write it.def average(n: list[int]): -> float, which puts->after the colon.
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.
Optional[int]means the same asint | None, but needsfrom typing import Optional. This way of writing it is from before Python 3.10, and you will still see it often in older code.Union[int, str]fromtypingis the same asint | str: the value may be an int or a str.- If the hint of the function above is only
-> int, but the result can beNone, mypy reports an error on thereturnline:Incompatible return value type (got "int | None", expected "int"). That is: the function returnsint | None, but its hint saysint.
⚠️ Hints mistaken for guards, and syntax that isn't Python
- Thinking hints check types. Python still runs
total_price("15", 3)and prints151515. To find a mistake like that one, run mypy. Data from outside (input, files) arrives as strings, and a hint does not change that: convert the type yourself withint(). - Another language's syntax. Syntax means the rules for writing code.
list<int>and-> floatafter the colon break Python's rules, so the result isSyntaxError: invalid syntax. Writelist[int], and put->before the colon. Listwithout an import. The result isNameError: name 'List' is not defined. Uselist[int], which needs no import.- Forgetting
None. A function that can returnNoneis written-> int | None. Then checkis Nonebefore you use its result.
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.