Type hints
Last updated
A function that wants a number of days will happily take the text "3", and give a strange answer. In this lesson you'll write down what types a function takes and gives back, for lists and dicts too, say when a value might be None, and let a tool called mypy check it all before the program runs.
By the end of this lesson you can
- Add type hints to names, parameters and return values
- Write hints for collections, like
list[str]anddict[str, int], and for a value that might beNone - Explain why Python runs code with the wrong types anyway, and catch it with
mypy
Saying what types you mean
A type hint says what type of value a name should hold. Write it after the name with a colon: days_late: int. After a function’s brackets, -> int says what type it gives back.
Watch it run. The hints don’t change what the program does at all.
So what are they for? For people, first: fine_for(days_late: int) -> int tells you how to call the function without reading its body. And for tools: Python keeps the hints (line 11 prints them), and your editor and a checker called mypy read them to spot mistakes.
Hints are optional. Most programs put them on functions, where they help most, and leave them off plain names like total on line 9, where the type is obvious.
Lists, dicts and tuples
For a collection, the hint says what’s inside too, in square brackets. list[str] is a list of text. dict[str, int] is a dict whose keys are text and whose values are whole numbers. A tuple lists the type of each item in order: tuple[str, int].
The hint on find says a lot in one line: give it a list of titles and a word, and it gives back a list of titles.
Python doesn’t check
fine_for says it wants an int. Line 5 gives it what input returns. Press Run, with 3 in the input box.
No error, just a wrong answer: "3" * 25 is the text "3" repeated 25 times. Python doesn’t check type hints when the program runs. They’re notes for people and tools, and Python ignores them. That’s different from Rust or Java, where the wrong type stops the program before it starts.
mypy does
mypy reads your code and its hints without running it, and reports every place the types don’t fit. Install it into your project’s virtual environment, as in lesson 2.9, and give it the file from step 3:
(.venv) > python -m pip install mypy
(.venv) > mypy fines.py
fines.py:6: error: Argument 1 to "fine_for" has incompatible type "str"; expected "int" [arg-type]
Found 1 error in 1 file (checked 1 source file)Line 6 passes a str where fine_for wants an int: the bug from step 3, found before anyone ran the program. After the fix, with int(input(...)):
(.venv) > mypy fines.py
Success: no issues found in 1 source filemypy and pytest work well together: mypy catches the wrong kind of value everywhere at once, and tests check the answers. Most editors can show mypy’s errors as you type.
Maybe nothing: X | None
Some functions don’t always have an answer. find_title gives back the first title that contains a word, or None if none does. Its hint says so: str | None means "text, or None". The | reads as "or".
The program that uses it must check for None before treating the answer as text. is None is the way to ask whether a value is None:
Without the check, a search that finds nothing breaks. Press Run:
AttributeError: 'NoneType' object has no attribute 'upper'. Nothing matched "Zz", so found is None, and None has no .upper(). mypy spots this without running anything, because the hint warned it that found might be None:
(.venv) > mypy search.py
search.py:9: error: Item "None" of "str | None" has no attribute "upper" [union-attr]
Found 1 error in 1 file (checked 1 source file)Add the if found is None: check from the first program, and both Python and mypy are happy.
Check what you learned
Three questions. Pick an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Function Annotations
- Glossary: type hint: hints are optional and not enforced by Python, but useful to tools
- Built-in Types: Generic Alias Type: list[str] and dict[str, int]
- Built-in Types: Union Type: int | None
- typing: Support for type hints
- PEP 484: Type Hints
- PEP 604: Allow writing union types as X | Y
- The Rust Programming Language: Data Types: Rust checks types before the program runs
- The Java Language Specification: Chapter 4, Types, Values, and Variables: Java checks types when compiling