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 ...?
“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” A little background on the Mypy project.
Installing and running mypy This command makes mypy type check your program.py file and print out any errors it finds. Mypy will type check your code statically: this means that it will check for errors without ever running your code, just like a linter.
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
I prefer to suppress mypy errors based on 2 things:
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:
pyproject.toml
[tool.mypy]
show_error_codes = true
mypy.ini
[mypy]
show_error_codes = True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With