Sub topic 3
Checking your code with mypy or pyright
Prerequisites and scope
This chapter assumes you can write Python functions and classes, know the built-in types (int, str, list, dict, tuple), and can install packages with pip. It also assumes you have seen the annotation syntax name: type and -> type. Here you will install a static type checker, run it, and read what it reports.
A static type checker is a program that reads your source code without running it. It compares the types you declared with the way you use values, and it reports mismatches. The Python interpreter does not do this, so a checker is a separate tool you run yourself.
Why you need a separate tool
The interpreter stores annotations but never checks them. This function runs without error even though the call is wrong:
def add(a: int, b: int) -> int:
return a + b
print(add.__annotations__)
print(add("x", "y")) # runs and prints xy; a static checker reports an error hereThe call add("x", "y") works because + joins two strings. Nothing stops it at runtime. A checker catches it before you run the program.
The two most common checkers are:
- mypy is the original checker, maintained by the Python community. It is written in Python.
- pyright is a checker from Microsoft. It is written in TypeScript and is the engine behind the Pylance extension in VS Code.
Both read the same annotation syntax. They mostly agree, and they differ in details that are covered below.
Installing and running mypy
Install mypy into your project's virtual environment:
python -m venv .venv
source .venv/bin/activate
pip install mypySave the following as example.py:
def add(a: int, b: int) -> int:
return a + b
result: str = add(1, 2)
add("x", "y")Run the checker on the file:
mypy example.pyThe output looks like this:
example.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
example.py:5: error: Argument 1 to "add" has incompatible type "str"; expected "int" [arg-type]
example.py:5: error: Argument 2 to "add" has incompatible type "str"; expected "int" [arg-type]
Found 3 errors in 1 file (checked 1 source file)Each line has the same parts: file, line number, severity, a message, and an error code in square brackets. The code, such as arg-type or assignment, names the category of the problem. You will use these codes to silence or configure specific checks.
You can also check a whole directory with mypy src/, or a package with mypy -p mypackage.
Installing and running pyright
Pyright is distributed on npm, but the pyright package on PyPI installs a wrapper that downloads it for you:
pip install pyright
pyright example.pyThe output for the same file looks like this:
example.py:4:13 - error: Type "int" is not assignable to declared type "str"
"int" is not assignable to "str" (reportAssignmentType)
example.py:5:5 - error: Argument of type "Literal['x']" cannot be assigned to parameter "a" of type "int" in function "add"
"Literal['x']" is not assignable to "int" (reportArgumentType)
example.py:5:10 - error: Argument of type "Literal['y']" cannot be assigned to parameter "b" of type "int" in function "add"
"Literal['y']" is not assignable to "int" (reportArgumentType)
3 errors, 0 warnings, 0 informationsPyright reports a column as well as a line. Its rule names begin with report. Exact wording changes between versions, so treat the examples as the shape of the output rather than a fixed string.
Reading an error
Most errors follow one pattern: the checker infers or reads a type for an expression and finds that the place where the value is used expects a different type. To read an error, find the two types it names. One is what you have. The other is what is expected.
Take this example:
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})
print(name.upper())mypy reports:
example.py:5: error: Item "None" of "str | None" has no attribute "upper" [union-attr]The declared return type allows None, so the checker will not let you call a str method until you rule None out. The fix is a check that narrows the type:
def find_user(user_id: int, users: dict[int, str]) -> str | None:
return users.get(user_id)
name = find_user(1, {1: "Ada"})
if name is not None:
print(name.upper())Inside the if block the checker treats name as str. Narrowing gets its own chapter, so here the point is only that the error message pointed at a real gap in the code.
Checking unannotated code
A checker only checks what it can see. By default, mypy skips the body of a function that has no annotations at all. It treats the parameters of that function as Any, a type that matches everything. Pyright is stricter: it infers types for unannotated code and checks it.
This difference matters when you adopt hints in an existing project. A clean mypy run may mean "no errors found" or only "little was checked." Two mypy options address this:
--check-untyped-defschecks the bodies of unannotated functions.--disallow-untyped-defsreports any function that lacks annotations.
Configuring the checker
Both tools read settings from pyproject.toml, so the whole team uses the same rules. A mypy configuration:
[tool.mypy]
python_version = "3.12"
strict = true
files = ["src"]A pyright configuration:
[tool.pyright]
include = ["src"]
pythonVersion = "3.12"
typeCheckingMode = "strict"Pyright's modes are off, basic, standard, and strict. The strict setting in mypy turns on a group of flags, including --disallow-untyped-defs, --warn-return-any, and --no-implicit-optional. Strict mode is useful for new code. For an existing codebase it usually produces too many errors at once, so start with defaults and tighten gradually.
Silencing an error
Sometimes the checker is wrong, or you cannot fix a problem yet, for example when a third-party library has no type information. Add a comment to the line:
import json
data = json.loads("[1, 2]")
value: int = data[0] # type: ignore[no-any-return]Use the specific error code in brackets. A bare # type: ignore hides every error on that line, including ones you add later. To catch ignores that are no longer needed, enable warn_unused_ignores in mypy or reportUnnecessaryTypeIgnoreComment in pyright. Pyright also accepts # pyright: ignore[ruleName].
For missing library types, mypy reports import-untyped or import-not-found. Many popular libraries have separate stub packages named types-<library>, such as types-requests. Install them with pip and the error goes away.
Where the checker fits in your workflow
Checkers pay off most when they run automatically. Three common places:
- In your editor. Pylance runs pyright as you type. The mypy plugin or a language server shows mypy errors inline.
- Before commit. A pre-commit hook runs the checker on changed files.
- In continuous integration. The build fails if the checker reports errors.
Use the diagram below to see the loop.
Running the same tool with the same configuration in all three places avoids the situation where code passes locally and fails in CI.
mypy or pyright
| Question | mypy | pyright |
|---|---|---|
| Unannotated functions | Skipped by default | Inferred and checked |
| Speed on large projects | Slower, with an incremental cache | Faster, with watch mode |
| Editor integration | Plugins and language servers | Built into Pylance |
| Configuration | `[tool.mypy]` | `[tool.pyright]` |
Neither is always right. Pick one for the project and run only that one in CI. If you maintain a public library, some teams run both, because users of the library may use either and the two sometimes disagree on edge cases.
Common mistakes
- Running the checker with the wrong interpreter. If the checker cannot see your installed packages, it reports missing imports. Run it from the virtual environment, or point it at the environment with
--python-executable(mypy) orvenvPathandvenv(pyright). - Ignoring errors in bulk. A bare
# type: ignoreon many lines removes the benefit of checking. - Treating
Anyas a type. An unannotated parameter isAnyin mypy's default mode, so errors involving it are never reported. - Expecting runtime errors. The checker does not change how the program behaves. If you want runtime validation, you need a separate library.
Exercise
You run mypy app.py and get no errors, but the file contains def total(items): return sum(items) and a call total("abc"). Why does mypy report nothing, and which option makes it check this function?
Show answer
The function has no annotations, so mypy skips its body by default and treats its parameters as Any, which accepts any argument. Annotating the function (for example def total(items: list[int]) -> int) makes the call total("abc") an error. The --check-untyped-defs option checks the body of unannotated functions, and --disallow-untyped-defs reports functions that lack annotations so you can add them.
Exercise
A teammate adds # type: ignore to a line to silence an error. Name one problem with this and a better alternative.
Show answer
A bare # type: ignore hides every error on the line, including new ones introduced later, and it stays after the underlying problem is fixed. Use a specific code such as # type: ignore[arg-type], and enable warn_unused_ignores (mypy) or reportUnnecessaryTypeIgnoreComment (pyright) so stale ignores are reported.