Checking Types with mypy

mypy reads your type hints and every call without running the code, and reports each place where a value can't be what its hint promises, such as text passed as a price or a None that the next line uses as text.

Journeyman · Python · Software Development · Updated

By

After this lesson you can

  • Install mypy in a virtual environment, run it on a project and read what its messages say
  • Fix the code mypy reports before it runs, such as a value that may be None

Key takeaways

  • mypy is a type checker. It reads your code and its hints without running anything, and reports each line where a value doesn't match its hint.
  • Each message names the file, the line, what's wrong and a code in square brackets, such as arg-type, and the last line says how many errors it found.
  • When a hint says a value can be None, mypy refuses any line that uses it as something else until the code checks for None first.
  • mypy skips functions that have no hints at all, and disallow_untyped_defs in pyproject.toml makes it report them instead.

A type hint is a promise: price: float says the price is a number. Python never checks that promise, so a wrong value travels through the program until it comes out as a wrong total on a bill, or a crash for one member at the front desk, weeks after the code was written. You'll use a type checker on any project where a bug like that costs more than a minute: a program you hand in for a grade, code a team shares, a tool you run every week.

The example is Peak Fitness, a gym, and the code its front desk runs.

A promise nobody checks

Here's the gym's cost function, with its hints, and a call that breaks the promise:

def membership_cost(price: float, months: int) -> float:
    return price * months


print(membership_cost("29.5", 3))
29.529.529.5

Python ran it and printed nonsense. A spell checker would have caught a typo like this in an essay before you handed it in, without anyone reading the essay aloud. mypy (read "my-pie") is that checker for Python. It's a type checker: it reads your code and its hints without running anything, and reports every place where a value can't be what its hint promises.

Install mypy and run it

mypy is a package, so it goes in your project's virtual environment, as Virtual Environments and pip showed. With the environment on (the prompt starts with (.venv)):

pip install mypy==2.4.1
mypy --version
mypy 2.4.1 (compiled: yes)

Save the code above as gym.py and run mypy on the whole folder. mypy . is read "mypy dot": the dot means "this folder", and mypy checks every Python file in it (skipping the .venv folder):

mypy .
gym.py:5: error: Argument 1 to "membership_cost" has incompatible type "str"; expected "float"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Read it left to right: the file, gym.py; the line, 5; then what's wrong. The first argument of the call on line 5 is a str, and the hint asked for a float. The code in square brackets, arg-type, names the kind of mistake, which is handy when you search for it. The last line counts the errors.

Change line 5 to print(membership_cost(29.5, 3)) and run mypy . again:

Success: no issues found in 1 source file

A value that may be None

mypy's most useful catch is the bug that only happens sometimes. This function looks up a member's plan and returns None for someone who isn't a member, and its hint says so:

def plan_for(name: str, members: dict[str, str]) -> str | None:
    if name in members:
        return members[name]
    return None


members: dict[str, str] = {"Rosa": "plus", "Dev": "basic"}
plan = plan_for("Mia", members)
print(plan.upper())

With "Rosa" it prints PLUS. With "Mia", a visitor who isn't a member yet, it stops. Here's the terminal on Windows, from a file named members.py in the course folder:

Traceback (most recent call last):
  File "C:\Users\Sam\python-course\peak-fitness\members.py", line 9, in <module>
    print(plan.upper())
          ^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'upper'

You could test with Rosa a hundred times and never see it. mypy sees it without running anything:

members.py:9: error: Item "None" of "str | None" has no attribute "upper"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

plan is a str | None, and None has no .upper(). The fix is to deal with None first. plan is None asks whether plan is None; Python programmers write is None rather than == None:

def plan_for(name: str, members: dict[str, str]) -> str | None:
    if name in members:
        return members[name]
    return None


members: dict[str, str] = {"Rosa": "plus", "Dev": "basic"}
plan = plan_for("Mia", members)
if plan is None:
    print("Mia isn't a member yet.")
else:
    print(plan.upper())
Mia isn't a member yet.

mypy knows that inside the else, plan can't be None, so it says Success: no issues found in 1 source file.

Make mypy check every function

mypy has one surprise: it skips any function with no hints at all, so code without hints always passes. A project tells mypy to report those functions in a settings file, pyproject.toml, in the project's folder:

[tool.mypy]
disallow_untyped_defs = true

[tool.mypy] starts mypy's settings, and disallow_untyped_defs = true says "a function without hints is an error". Now a function such as def membership_cost(price, months): gets error: Function is missing a type annotation [no-untyped-def], and once you add its hints, mypy checks every call to it too.

To see mypy's messages while you type, install the Mypy Type Checker extension by Microsoft from VS Code's Extensions view. It underlines each line mypy reports, and the Problems panel (View > Problems) lists them:

VS Code with the Mypy Type Checker extension: the line print(plan.upper()) in members.py is underlined, and the Problems panel below lists mypy's message for line 9: plan can be None, and None has no attribute "upper"

Check yourself

2 questions to try on the lesson page.

So what

mypy turns a bug that shows up for one member, weeks from now, into a line number you can fix today, before the code has run even once.

Key terms

Related