Configuring warnings
The follow flags enable warnings for code that is sound but ispotentially problematic or redundant in some way.
—warn-redundant-casts
- This flag will make mypy report an error whenever your code usesan unnecessary cast that can safely be removed.
—warn-unused-ignores
- This flag will make mypy report an error whenever your code usesa
# type: ignore
comment on a line that is not actuallygenerating an error message.
This flag, along with the —warn-redundant-casts
flag, are bothparticularly useful when you are upgrading mypy. Previously,you may have needed to add casts or # type: ignore
annotationsto work around bugs in mypy or missing stubs for 3rd party libraries.
These two flags let you discover cases where either workarounds areno longer necessary.
—no-warn-no-return
By default, mypy will generate errors when a function is missingreturn statements in some execution paths. The only exceptionsare when:
- The function has a
None
orAny
return type - The function has an empty body or a body that is justellipsis (
…
). Empty functions are often used forabstract methods. Passing in—no-warn-no-return
will disable these errormessages in all cases.
- The function has a
—warn-return-any
- This flag causes mypy to generate a warning when returning a valuewith type
Any
from a function declared with a non-Any
return type.
—warn-unreachable
- This flag will make mypy report an error whenever it encounterscode determined to be unreachable or redundant after performing type analysis.This can be a helpful way of detecting certain kinds of bugs in your code.
For example, enabling this flag will make mypy report that the x > 7
check is redundant and that the else
block below is unreachable.
- def process(x: int) -> None:
- # Error: Right operand of 'or' is never evaluated
- if isinstance(x, int) or x > 7:
- # Error: Unsupported operand types for + ("int" and "str")
- print(x + "bad")
- else:
- # Error: 'Statement is unreachable' error
- print(x + "bad")
To help prevent mypy from generating spurious warnings, the “Statement isunreachable” warning will be silenced in exactly two cases:
- When the unreachable statement is a
raise
statement, is anassert False
statement, or calls a function that has theNoReturn
return type hint. In other words, when the unreachable statementthrows an error or terminates the program in some way. - When the unreachable statement was intentionally marked as unreachableusing Python version and system platform checks.
Note
Mypy currently cannot detect and report unreachable or redundant codeinside any functions using Type variables with value restriction.
This limitation will be removed in future releases of mypy.