Skip to content

Commit 057f8ad

Browse files
authored
use is_same_type when determining if a cast is redundant (python#18588)
while working on python#18540 (which my original prototype based the code on `warn-redundant-casts`) I noticed the suggestion [here](python#18540 (comment)) would probably make sense to apply to redundant-cast as well! I also made sure to include the example from the [original implementation](python#1705 (comment)) just to make sure I wasn't regressing that as well since it seemed related.
1 parent 99e2688 commit 057f8ad

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

mypy/checkexpr.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4696,8 +4696,8 @@ def visit_cast_expr(self, expr: CastExpr) -> Type:
46964696
options = self.chk.options
46974697
if (
46984698
options.warn_redundant_casts
4699-
and not isinstance(get_proper_type(target_type), AnyType)
4700-
and source_type == target_type
4699+
and not is_same_type(target_type, AnyType(TypeOfAny.special_form))
4700+
and is_same_type(source_type, target_type)
47014701
):
47024702
self.msg.redundant_cast(target_type, expr)
47034703
if options.disallow_any_unimported and has_any_from_unimported_type(target_type):

test-data/unit/check-warnings.test

+26
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,32 @@ a: Any
4242
b = cast(Any, a)
4343
[builtins fixtures/list.pyi]
4444

45+
[case testCastToObjectNotRedunant]
46+
# flags: --warn-redundant-casts
47+
from typing import cast
48+
49+
a = 1
50+
b = cast(object, 1)
51+
52+
[case testCastFromLiteralRedundant]
53+
# flags: --warn-redundant-casts
54+
from typing import cast
55+
56+
cast(int, 1)
57+
[out]
58+
main:4: error: Redundant cast to "int"
59+
60+
[case testCastFromUnionOfAnyOk]
61+
# flags: --warn-redundant-casts
62+
from typing import Any, cast, Union
63+
64+
x = Any
65+
y = Any
66+
z = Any
67+
68+
def f(q: Union[x, y, z]) -> None:
69+
cast(Union[x, y], q)
70+
4571
-- Unused 'type: ignore' comments
4672
-- ------------------------------
4773

0 commit comments

Comments
 (0)