Sub topic 13
Silencing errors deliberately: ignore comments and cast
This chapter assumes you can run mypy or Pyright on a project and read their error messages. It also assumes you know what Any is and how narrowing works. Sometimes a checker reports an error you cannot or should not fix right now. Python gives you two tools for that: ignore comments, which hide an error, and cast, which overrides a type. Both are useful, and both can hide real bugs when overused.
What each tool does
An ignore comment tells the checker not to report errors on one line. It does not change any types. A cast tells the checker to treat a value as a different type from that point on. It does not check or convert anything at runtime.
| Tool | Effect on the checker | Effect at runtime |
|---|---|---|
| `# type: ignore` | Hides errors on that line (both tools) | None |
| `# type: ignore[code]` | mypy hides only that error code. Pyright hides all errors on the line. | None |
| `# pyright: ignore[rule]` | Pyright hides only the named rule. mypy ignores the comment. | None |
| `cast(T, value)` | Treats `value` as type `T` | Returns `value` unchanged |
Ignore comments
Here is the example from the topic plan, with both ignore forms and a cast:
from typing import cast
def parse(value: object) -> str:
text = cast(str, value) # we know callers pass a str
return text.strip()
result: int = "abc" # type: ignore[assignment]
other: int = "abc" # pyright: ignore[reportAssignmentType]Both result and other assign a str to an int variable, which is an error in both checkers. The first comment uses mypy's error code, assignment. The second uses Pyright's rule name. In older Pyright releases this rule was reported as reportGeneralTypeIssues, so check the name in your checker's output.
Always name the error
A bare # type: ignore hides every error on its line, including errors you have not seen yet. If someone later edits that line and introduces a different bug, the comment hides it too. Prefer the targeted forms:
- With mypy, write
# type: ignore[code]. The code appears in square brackets at the end of each error message. - With Pyright, write
# pyright: ignore[rule]. The rule name appears in parentheses at the end of each message.
Pyright reads # type: ignore comments by default, which is why one comment can serve both tools. It does not use the code inside the brackets, so # type: ignore[assignment] hides all Pyright errors on the line. If your team runs both checkers, put both comments on the line, separated by a space or semicolon-free comment text:
value: int = "abc" # type: ignore[assignment] # pyright: ignore[reportAssignmentType]Find stale and unexplained ignores
An ignore comment can outlive the problem it was hiding. Turn on the checks that report these:
[tool.mypy]
warn_unused_ignores = true
enable_error_code = ["ignore-without-code"]
[tool.pyright]
reportUnnecessaryTypeIgnoreComment = "warning"warn_unused_ignoresmakes mypy report an ignore that hides nothing. Strict mode already enables it.ignore-without-codemakes mypy report a bare# type: ignore.reportUnnecessaryTypeIgnoreCommentmakes Pyright report unneeded# type: ignoreand# pyright: ignorecomments. It is off by default, including in strict mode.
Placement and scope
Put the comment on the line where the checker reports the error. For a statement that spans several lines, run the checker and move the comment until the error disappears. Where the tools report the error can differ between them.
You can also silence larger areas:
- A
# type: ignorecomment on its own line at the top of a file, before any code, hides all errors in that file. Both tools honor it. Avoid it, because it also hides errors in code you add later. - mypy accepts
# mypy: ignore-errorsat the top of a file. - In
pyproject.toml, mypy can ignore whole modules with[[tool.mypy.overrides]], and Pyright can skip paths withignore:
[[tool.mypy.overrides]]
module = "legacy.*"
ignore_errors = true
[tool.pyright]
ignore = ["src/legacy"]Configuration-level ignores are easier to find and remove than comments spread across a file. They are the better choice when a whole legacy package is not ready for checking.
cast
typing.cast(T, value) returns value exactly as it was. At runtime it does nothing, apart from the cost of a function call. The checker, however, treats the result as type T.
import json
from typing import cast
def load_names(path: str) -> list[str]:
with open(path) as f:
data = json.load(f) # json.load returns Any
return cast(list[str], data)If the file contains [1, 2, 3], this function still returns it as a list[str], and the error appears later, far from the cause. A cast moves a claim from the checker to you. Nothing verifies it.
Prefer checks the checker understands
When you can verify the type at runtime, do that and let narrowing do the work:
import json
def load_names(path: str) -> list[str]:
with open(path) as f:
data = json.load(f)
if not isinstance(data, list) or not all(isinstance(x, str) for x in data):
raise ValueError("expected a JSON list of strings")
return dataNarrowing with isinstance(data, list) gives the checker a list[Any], which is accepted as list[str]. This version also fails early with a clear message if the data is wrong. If the same check appears in many places, write a function that returns TypeGuard[list[str]] (or TypeIs, available in newer typing releases) so callers narrow the value automatically.
A cast is reasonable when the checker lacks information that you really have. Typical cases are values returned from untyped libraries, results of dynamic lookups, and code where an invariant is enforced somewhere the checker cannot see. Leave a short comment saying why it is safe.
Redundant casts
A cast to the type a value already has adds noise. mypy can report it with warn_redundant_casts, which strict mode enables. Pyright reports it under reportUnnecessaryCast, which is also part of strict mode.
Choosing between them
Use an ignore comment when the line is not wrong but the checker cannot express it. Examples are a checker bug, a library with incorrect stubs, or a deliberate test of invalid input. Use cast when you want a specific type to flow into later code. An ignore comment only hides the error, so the value keeps its old type afterward.
Common mistakes
- Using a bare
# type: ignoreand hiding a second, unrelated error on the same line. - Casting to silence an
Optionalerror instead of adding aNonecheck. If the value is everNone, you get anAttributeErrorat runtime, which is the failure the checker was warning you about. - Casting from
Anyand believing the data was validated. Parsed JSON, ORM results, and**kwargsare all unchecked. - Leaving ignore comments in place after upgrading a library. Enable the unused-ignore checks above so that stale comments are reported.
Exercise
A function returns json.loads(text) and the checker reports that you are returning Any from a function declared to return dict[str, int]. A teammate suggests wrapping the return value in cast(dict[str, int], ...). What risk does that introduce, and what is a safer approach?
Show answer
The cast makes the error disappear, but nothing checks the data at runtime. If the JSON holds other keys or value types, the wrong type flows through the program and fails later, away from the cause. A safer approach is to validate the result, for example with isinstance(data, dict) and a check that the values are int, and raise an error if the check fails. Alternatively, put the validation in a TypeGuard function so the checker narrows the type for you.
Exercise
Your project runs both mypy and Pyright. Write one line that assigns the string "x" to an int variable and silences the error in both checkers using targeted comments. Which settings would report these comments once the error is fixed?
Show answer
count: int = "x" # type: ignore[assignment] # pyright: ignore[reportAssignmentType]. mypy reports the stale comment when warn_unused_ignores = true is set (strict mode includes it). Pyright reports it when reportUnnecessaryTypeIgnoreComment is enabled, which strict mode does not do on its own.