Can I suppress mypy errors in-line?

Question:

I recently made the mistake of opening my $PYTHONSTARTUP file with mypy syntax checking enabled. As a result, I started getting this error:

startup.py|79 col 2 error| Incompatible types in assignment (expression has type "HistoryPrompt", variable has type "str")

On line 79:

sys.ps1 = HistoryPrompt()

I immediately thought, “By Jove, mypy! You’re entirely correct! And yet, that is exactly what I want to do, so you’re also wrong!”

I went looking to see if there was some kind of “stub” for the sys module, but couldn’t find anything. I’m guessing that mypy is determining the type by looking at the value stored in the variable (default is “>>> “, which is a str).

In reality, of course, the type needs to be the non-existant typing.Stringifiable, indicating an object that will respond to str(x).

Having reached that dead end, I went looking for a way to tell mypy to suppress the error. So many of the other tools support # noqa: xxx that I figured there must be something, right?

Wrong. Or at least, I couldn’t find it in my version, which is: mypy 0.670

So I devised a hack clever work-around:

import typing

# Work around mypy error: Incompatible types in assignment
suppress_mypy_error: typing.Any = HistoryPrompt()
sys.ps1 = suppress_mypy_error

My question is this: Is there a way to suppress this particular error in-line (best), or in mypy.ini, or by submitting a PR to python/mypy, or …?

Asked By: aghast

||

Answers:

To explicitly suppress MyPy on a specific line, add a comment of the form # type: ignore.

To suppress MyPy for an entire module, add the same comment at the top of the module.

Source: https://mypy.readthedocs.io/en/latest/common_issues.html#spurious-errors-and-locally-silencing-the-checker

Answered By: 0az

Overview

I prefer to suppress mypy errors based on 2 things:

  • specific lines (your question), and
  • specific error.

Example

For example, the # type: ignore [no-untyped-call]:

# ignore mypy error because azure has broken type hints.
# See https://github.com/Azure/azure-sdk-for-python/issues/20083 (the issue is closed but the problem remains)
exception = azure.core.exceptions.ResourceNotFoundError("Test") # type: ignore [no-untyped-call]

You can find out the "error code" (e.g. no-untyped-call) in the mypy output by configuring mypy with:

  • in pyproject.toml
[tool.mypy]
show_error_codes = true
  • or in mypy.ini
[mypy]
show_error_codes = True

Benefits

  • Documentation in code: You can see exactly what error is being suppressed.
  • You won’t ignore other errors by mypy. Otherwise, that line could be a source of bugs in the future and mypy would not warn you.
Answered By: Ben Butterworth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.