Sub topic 12
Turning on strict checking
This chapter assumes you can run mypy and Pyright, read their output, and write annotations for functions and variables. It also assumes you know what Any means in gradual typing. Here you will see what strict mode turns on in each tool, which errors it adds, and how to apply it to part of a codebase.
What strict mode changes
By default, both checkers are lenient. mypy skips the body of any function that has no annotations. Pyright's standard mode, which is its default, accepts missing annotations and infers what it can. Strict mode removes that leniency. It requires annotations, forbids silent Any, and flags code that suggests a mistake.
The two tools implement this differently.
| Aspect | mypy `strict = true` | Pyright `typeCheckingMode = "strict"` |
|---|---|---|
| What it is | A bundle of individual flags | A preset that raises many rules to errors |
| Missing annotations | `disallow_untyped_defs`, `disallow_incomplete_defs` | `reportMissingParameterType` |
| Bare generics such as `list` | `disallow_any_generics` | `reportMissingTypeArgument` |
| Untyped code bodies | `check_untyped_defs` | Always checked |
| Unknown or `Any` values | `warn_return_any`, `disallow_untyped_calls` | `reportUnknownVariableType`, `reportUnknownMemberType`, `reportUnknownArgumentType` |
| Useless code | `warn_redundant_casts`, `warn_unused_ignores` | `reportUnnecessaryCast`, `reportUnnecessaryIsInstance`, `reportUnnecessaryComparison` |
| Per-file switch | Not available for `strict` itself | `# pyright: strict` comment |
The exact flag set changes between releases, so run mypy --help and read the Pyright configuration documentation for your installed versions. Do not rely on a list you remember.
Enabling it
The configuration from the earlier chapter already enables both modes:
[tool.mypy]
python_version = "3.12"
strict = true
files = ["src"]
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"
include = ["src"]You can also try strict mode once from the command line, without editing the config:
mypy --strict src/
pyright --level error src/Running mypy --strict first is a cheap way to count how many errors a rollout would cause.
What strict mode catches
Take an untyped function that passes under default settings:
def total(prices, tax=0.2):
return sum(prices) * (1 + tax)mypy in strict mode reports that the function is missing a type annotation (no-untyped-def). Pyright in strict mode reports a missing annotation for prices (reportMissingParameterType). It also reports that the type of prices is unknown (reportUnknownParameterType). Both messages are shortened here.
The fix is to state the types:
from collections.abc import Iterable
def total(prices: Iterable[float], tax: float = 0.2) -> float:
return sum(prices) * (1 + tax)Bare generics
A bare list annotation means list[Any]. Strict mode rejects it because the Any is hidden.
def count_items(items: list) -> int: # flagged: missing type parameters
return len(items)
def count_items_ok(items: list[str]) -> int:
return len(items)mypy reports this through disallow_any_generics. Pyright reports it through reportMissingTypeArgument.
Returning Any
Values that come from untyped libraries or from json.loads are Any. Without strict mode, they flow into your typed functions unchecked.
import json
def load_count(text: str) -> int:
data = json.loads(text)
return data["count"] # mypy strict: Returning Any from function declared to return "int"mypy's warn_return_any flags the return. To fix it, give the value a declared type at the point where you trust it:
import json
def load_count(text: str) -> int:
count: int = json.loads(text)["count"]
return countThis is still a trust decision, because nothing checks the JSON at runtime. If the data comes from outside your program, validate it. Use isinstance checks, a TypedDict with a validator, or a library built for that purpose.
Unknown versus Any
Pyright distinguishes Any (an explicit choice) from Unknown (the checker could not work out a type). Strict mode reports Unknown values and values that are partly unknown, such as list[Unknown]. This is why Pyright strict output can feel noisier than mypy's when you import an untyped library. The Unknown spreads to every variable that touches it.
Strict for part of the code
Turning on strict mode for a whole legacy project at once usually produces hundreds or thousands of errors. A better approach is to make new and cleaned-up code strict, and keep old code lenient until you reach it.
For mypy, start with global strict mode and relax it for named modules:
[tool.mypy]
strict = true
[[tool.mypy.overrides]]
module = ["legacy", "legacy.*"]
disallow_untyped_defs = false
disallow_incomplete_defs = false
disallow_untyped_calls = false
check_untyped_defs = falseFor Pyright, do the reverse: start from standard and list the paths that are strict.
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "standard"
include = ["src"]
strict = ["src/core", "src/billing"]A single file can also opt in with a comment on its own line near the top:
# pyright: strictFailure modes
- Ignores accumulate. Strict mode pushes people to add
# type: ignoreto get a green build. mypy'swarn_unused_ignoresand Pyright'sreportUnnecessaryTypeIgnoreComment(which is off by default, even in strict) report ignores that no longer suppress anything. Turn them on so stale ignores get removed. - Annotating with
Anyto silence errors. An explicitAnyis allowed in strict mode, because it is a stated choice. It still disables checking for that value. ReviewAnyin code review. - Unknown third-party types. A library with no stubs and no
py.typedmarker makes strict mode noisy. See the stubs chapter for installing stubs. As a last resort, mypy acceptsignore_missing_imports = truefor a single module. - Version drift. A new checker release can add checks to strict mode. Pin the version of mypy and Pyright in your dev dependencies and upgrade on purpose.
Choosing a strategy
Use strict mode from the start in a new project, because it is cheapest then. In an existing project, make strict the default for new modules and move old ones across as you touch them. If you must pick one tool for the strictest checking, Pyright's Unknown tracking catches more leaks from untyped libraries. mypy's strict is easier to read as a list of named flags that you can switch on one at a time.
Exercise
A mypy project has strict = true. One legacy module, legacy.reports, produces hundreds of no-untyped-def errors. You cannot annotate it this week. How do you keep strict mode for the rest of the project, and why can't you write strict = false in the override?
Show answer
Add a [[tool.mypy.overrides]] section with module = ["legacy.reports"] and set the specific flags to false, such as disallow_untyped_defs = false, disallow_incomplete_defs = false, and check_untyped_defs = false. strict is a global shortcut for a group of flags. It is not accepted in a per-module override, so you must set the flags it implies one by one.
Exercise
Pyright in strict mode reports that the type of rows is list[Unknown] after rows = untyped_lib.fetch(). What is the difference between Unknown and Any, and what is one way to fix it?
Show answer
Any is a type you wrote on purpose. Unknown means Pyright could not infer a type, for example because the library has no annotations or stubs. Fix it by installing stubs or a typed version of the library, or by declaring the type where you trust it, for example rows: list[dict[str, int]] = untyped_lib.fetch().