Spurious errors and locally silencing the checker
You can use a # type: ignore
comment to silence the type checkeron a particular line. For example, let’s say our code is usingthe C extension module frobnicate
, and there’s no stub available.Mypy will complain about this, as it has no information about themodule:
- import frobnicate # Error: No module "frobnicate"
- frobnicate.start()
You can add a # type: ignore
comment to tell mypy to ignore thiserror:
- import frobnicate # type: ignore
- frobnicate.start() # Okay!
The second line is now fine, since the ignore comment causes the namefrobnicate
to get an implicit Any
type.
Note
You can use the form # type: ignore[<code>]
to only ignorespecific errors on the line. This way you are less likely tosilence unexpected errors that are not safe to ignore, and thiswill also document what the purpose of the comment is. SeeError codes for more information.
Note
The # type: ignore
comment will only assign the implicit Any
type if mypy cannot find information about that particular module. So,if we did have a stub available for frobnicate
then mypy wouldignore the # type: ignore
comment and typecheck the stub as usual.
Another option is to explicitly annotate values with type Any
–mypy will let you perform arbitrary operations on Any
values. Sometimes there is no more precise type you can use for aparticular value, especially if you use dynamic Python featuressuch as getattr
:
- class Wrapper:
- ...
- def __getattr__(self, a: str) -> Any:
- return getattr(self._wrapped, a)
Finally, you can create a stub file (.pyi
) for a file thatgenerates spurious errors. Mypy will only look at the stub fileand ignore the implementation, since stub files take precedenceover .py
files.