Bigger programs · lesson 11 of 12
Parts in this lesson
Adays: inta type hint
B-> intwhat a function gives back
Clist[str]a list of text
Dstr | Nonetext, or nothing
Emypy file.pychecks the hints

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] and dict[str, int], and for a value that might be None
  • 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.

Step 1 code main.py
Edit the code, then run it again

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].

Step 2 code main.py
Edit the code, then run it again

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.

Step 3 code main.py
Edit the code, then run it again

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 file

mypy 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.

mypy reports an error on a line. What happens if you run the program anyway?

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:

Step 5 code main.py
Edit the code, then run it again

Without the check, a search that finds nothing breaks. Press Run:

Step 5 code main.py
Edit the code, then run it again

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.

What does this function take, and what does it give back?
def average(pages: list[int]) -> float:
    return sum(pages) / len(pages)
def due_in(days: int) -> str:. You call due_in("14"). What does Python do?
A function finds a member by name, and there may be no such member. Which return hint fits?

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.

All sources for Simple Python