mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Add redundant-annotation warning

Open grayjk opened this issue 1 month ago • 9 comments

Relates to #18540

Adds a warning for redundant-annotation where a function local variable annotation type is the same as the inferred type

Based heavily on the code from @asottile in the issue

grayjk avatar Nov 14 '25 23:11 grayjk

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Nov 15 '25 00:11 github-actions[bot]

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Nov 15 '25 16:11 github-actions[bot]

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Nov 16 '25 15:11 github-actions[bot]

When --disallow-any-generic is enabled, it requires an annotation for:

a = (None, [])

that conflicts with the warning from --warn-redundant-annotation

grayjk avatar Nov 17 '25 17:11 grayjk

@JukkaL do you have opinions on how this interacts with (maybe) redefinition? I forgot what heuristics you've mentioned using for it before.

A5rocks avatar Nov 18 '25 16:11 A5rocks

Testing this on an internal project that uses sphinx-autodoc-typehints, this branch warns on a redundant type hint that is meant for the sphinx generated documentation. An unfortunate downside

grayjk avatar Nov 21 '25 14:11 grayjk

I'd say this check should only fire for function locals. Redundant annotations at top level (globals) and class members should be fine - they declare the public interface explicitly. If I say

STEPS_LIMIT: int = 3

at top level, I want it to mean "this is a max count of steps to perform, some integer, but make no assumptions about its value". It should not be reinterpreted as final or literal, for example, and the explicit type hint means "yes, really an int, it is not going to become a float later without semver-major update, but its value could change to 20 in a patch release".

This would also resolve your sphinx-autodoc-typehints issue, I believe?

sterliakov avatar Nov 24 '25 11:11 sterliakov

I'd say this check should only fire for function locals.

Updated to this

grayjk avatar Nov 24 '25 17:11 grayjk

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Nov 24 '25 18:11 github-actions[bot]