Sub topic 3
Configuring mypy and Pyright in `pyproject.toml`
This chapter assumes you can run Python 3.10+ code, install packages with pip, and use a command line. The examples configure both checkers for one src directory.
Configure both checkers
pyproject.toml is a project configuration file. Add one section for each checker:
[tool.mypy]
python_version = "3.12"
files = ["src"]
strict = true
[tool.pyright]
pythonVersion = "3.12"
include = ["src"]
typeCheckingMode = "strict"Both tools now check the same files with strict rules. Keep the Python version aligned with the version your project supports.
Strict checking and deliberate exceptions
Strict mode catches missing annotations, unsafe Any values, and other errors that basic checking may miss. Enable it for new code first if an existing project has many errors.
Use a targeted ignore only when you understand the error:
total: int = "unknown" # type: ignore[assignment]
count: int = "unknown" # pyright: ignore[reportAssignmentType]The comments suppress one error at one location. Error codes make later review easier.
cast changes what the checker believes without checking the value at runtime:
from typing import cast
def parse(value: object) -> str:
text = cast(str, value)
return text.strip()Use cast only when another guarantee proves the type. Prefer validation when data comes from users, files, or networks.
Third-party libraries
A library with inline annotations advertises support with a py.typed marker. For an untyped library, install a separate stub package when one exists:
python -m pip install types-requestsStubs are files containing type information without the library's implementation.
Differences between the checkers
Mypy and Pyright implement the same typing ideas, but inference, diagnostics, and configuration names differ. Pyright often provides fast editor feedback. Mypy fits naturally into Python-focused command-line and CI workflows. Choose one as the required check, then use the other as a supporting tool if its feedback helps.
Adopt checking incrementally
Start with one package or directory. Fix errors in changed files, avoid adding new ignores, and expand the checked boundary after the error count falls. Run the same command locally and in CI:
mypy src/
pyright src/Editors can run Pyright continuously, while CI provides a consistent merge gate.
Exercise
Why should a project use a targeted ignore comment instead of disabling type checking for an entire file?
Show answer
A targeted comment limits the exception to one known error, so other errors remain visible.