Sub topic 3
Running mypy and Pyright on your code
This chapter assumes you can annotate functions with simple types such as str and int, which the previous chapter covered. It also assumes you work in a virtual environment on Python 3.10 or newer. Here you will install both checkers, run them, read their output, and handle the setup problems that trip people up most often.
Installing the checkers
Both tools install from PyPI. Install them into the same virtual environment as your project, so they can see your dependencies.
python -m pip install mypy pyright
mypy src/
pyright src/mypy is a pure Python program. The pyright package on PyPI is a thin wrapper around the Node.js tool of the same name. If Node is not installed, the wrapper downloads a copy the first time you run it, so the first run needs network access and is slower.
You can also start mypy as a module with python -m mypy src/. This guarantees that mypy runs under the interpreter you expect, which is useful when several Python versions are installed.
Running a first check
Save this as app.py:
def greet(name: str) -> str:
return "Hello, " + name
greet("Ada")
greet(42) # flagged by the checker: int is not strRunning mypy app.py prints something like this:
app.py:6: error: Argument 1 to "greet" has incompatible type "int"; expected "str" [arg-type]
Found 1 error in 1 file (checked 1 source file)Running pyright app.py prints something like this:
/home/you/project/app.py
/home/you/project/app.py:6:7 - error: Argument of type "Literal[42]" cannot be assigned to parameter "name" of type "str" in function "greet"
"Literal[42]" is not assignable to "str" (reportArgumentType)
1 error, 0 warnings, 0 informationsThe exact wording changes between versions, so match on the structure and not the text. The two reports contain the same facts:
- Location. mypy gives
file:line. Pyright givesfile:line:column, so it points at the offending argument. - Severity. Both use
error. Pyright also haswarningandinformation. - Rule identifier. mypy ends the line with an error code such as
arg-type. Pyright ends with a rule name such asreportArgumentType. You use these identifiers later to configure rules and to silence single errors. - Detail. Pyright adds indented lines that explain why the types are incompatible. mypy usually keeps the message to one line.
Note that Literal[42] appears in Pyright's message. Pyright keeps the exact value of a literal when it describes an argument. mypy reports the wider type int.
Choosing what to check
You can point each tool at files, directories, or both. mypy also accepts packages and modules by name.
| Goal | mypy | Pyright |
|---|---|---|
| One file | `mypy app.py` | `pyright app.py` |
| A directory, recursively | `mypy src/` | `pyright src/` |
| An importable package | `mypy -p mypkg` | not available |
| An importable module | `mypy -m mypkg.utils` | not available |
| The whole project from the current directory | `mypy .` | `pyright` |
| Re-run on every file change | not built in | `pyright --watch` |
mypy requires at least one target unless your configuration lists files. Pyright with no arguments checks the current directory, or whatever the include setting names. Both are covered in the configuration chapter.
Exit codes
CI systems and pre-commit hooks look at the exit status of a command. Both checkers exit with 0 when they find no errors and 1 when they report errors. Other non-zero values mean the tool itself failed, for example because of a bad option or an unreadable configuration file.
mypy src/
echo "mypy exit status: $?"
pyright src/
echo "pyright exit status: $?"Pyright warnings do not change the exit status. If you want warnings to fail the build, run pyright --warnings.
What happens during a run
Both tools follow the same broad sequence. They read configuration, collect the files to check, resolve every import, and only then check function bodies and expressions. The results are printed, and the exit status is set from them.
Import resolution is the stage where most first-day problems appear. The checker must find the source or stubs of every module you import. A failure there does not stop the run. The checker treats the unresolved module as Any, which hides errors in the code that uses it.
The checker must see your environment
A checker that cannot see your installed libraries cannot check calls into them. Two situations cause this most often.
First, the checker is installed in a different environment from the project. Running mypy from a global install reports your dependencies as missing:
app.py:1: error: Cannot find implementation or library stub for module named "requests" [import-not-found]Pyright reports the same condition like this:
app.py:1:8 - error: Import "requests" could not be resolved (reportMissingImports)The simplest fix is to install the checker into the project's virtual environment. If you prefer one global checker, tell it which interpreter to inspect:
mypy --python-executable .venv/bin/python src/
pyright --pythonpath .venv/bin/python src/On Windows the interpreter path is .venv\Scripts\python.exe.
Second, the library is installed but ships no type information. mypy reports a missing stub or a missing py.typed marker. Pyright reports reportMissingModuleSource or reportMissingTypeStubs. A later chapter covers stub packages. For now, recognize that "cannot find" and "no type information" are different problems.
A difference you will notice immediately
By default, mypy skips the bodies of functions that have no annotations at all. Pyright checks them and infers types from the code inside.
def total(prices):
return sum(prices) + "tax"Pyright reports that int and str cannot be added here. mypy reports nothing, because total has no annotations. To make mypy check unannotated functions, run mypy --check-untyped-defs src/ or set check_untyped_defs = true in its configuration. This is one reason the same project can be clean under one tool and noisy under the other.
Speed and caching
mypy stores results in a .mypy_cache directory, so later runs re-check only files that changed and the files that depend on them. Add this directory to .gitignore. For very large projects, mypy also has a daemon, started with dmypy run -- src/, which stays in memory between runs. Pyright is written in TypeScript, is generally faster on a cold start, and --watch keeps it running and re-checks on save.
Common mistakes
- Running the checker with no target.
mypyalone prints a usage message and exits with a non-zero status. - Installing the checker globally and expecting it to see virtual-environment packages.
- Treating a clean result as proof of correctness. A checker verifies annotations against code. It does not check values at runtime.
- Comparing counts between the tools. They have different defaults, so the numbers are not comparable.
Exercise
Your CI job runs mypy src/ and passes, but a colleague running pyright src/ sees an error in a function that has no annotations. Give the most likely reason, and one mypy option that would bring the tools closer together.
Show answer
By default mypy does not check the bodies of functions without annotations, while Pyright infers types and checks them. Running mypy with --check-untyped-defs, or setting check_untyped_defs = true in its configuration, makes mypy check those function bodies too.
Exercise
mypy reports Cannot find implementation or library stub for module named "requests" even though pip list shows requests installed in your virtual environment. What are two ways to fix this?
Show answer
The checker is probably running from a different environment than the one holding requests. Either install mypy into the project's virtual environment and run it from there, or keep the global install and pass --python-executable .venv/bin/python so mypy inspects the project's interpreter.