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:

  1. import frobnicate # Error: No module "frobnicate"
  2. frobnicate.start()

You can add a # type: ignore comment to tell mypy to ignore thiserror:

  1. import frobnicate # type: ignore
  2. 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 Anytype 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 Anyvalues. Sometimes there is no more precise type you can use for aparticular value, especially if you use dynamic Python featuressuch as getattr:

  1. class Wrapper:
  2. ...
  3. def __getattr__(self, a: str) -> Any:
  4. 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.