From d87bac9ad96ab05333873de94a5da5e55a2b1c6f Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Sun, 2 Feb 2025 14:24:01 -0500 Subject: [PATCH 1/2] use is_same_type when determining if a cast is redundant --- mypy/checkexpr.py | 2 +- test-data/unit/check-warnings.test | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 4b7e39d2042a..a7811fa45a12 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4688,7 +4688,7 @@ def visit_cast_expr(self, expr: CastExpr) -> Type: if ( options.warn_redundant_casts and not isinstance(get_proper_type(target_type), AnyType) - and source_type == target_type + and is_same_type(source_type, target_type) ): self.msg.redundant_cast(target_type, expr) if options.disallow_any_unimported and has_any_from_unimported_type(target_type): diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test index 90f40777d6b7..87bb1aa946b4 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -42,6 +42,21 @@ a: Any b = cast(Any, a) [builtins fixtures/list.pyi] +[case testCastToObjectNotRedunant] +# flags: --warn-redundant-casts +from typing import cast + +a = 1 +b = cast(object, 1) + +[case testCastFromLiteralRedundant] +# flags: --warn-redundant-casts +from typing import cast + +cast(int, 1) +[out] +main:4: error: Redundant cast to "int" + -- Unused 'type: ignore' comments -- ------------------------------ From ffab4d41e73c93eb8dd3cb5e87fdc72842d910d6 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Sun, 2 Feb 2025 16:02:14 -0500 Subject: [PATCH 2/2] don't report warn-redundant-cast to cast of Union of Any --- mypy/checkexpr.py | 2 +- test-data/unit/check-warnings.test | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index a7811fa45a12..0627391986ca 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4687,7 +4687,7 @@ def visit_cast_expr(self, expr: CastExpr) -> Type: options = self.chk.options if ( options.warn_redundant_casts - and not isinstance(get_proper_type(target_type), AnyType) + and not is_same_type(target_type, AnyType(TypeOfAny.special_form)) and is_same_type(source_type, target_type) ): self.msg.redundant_cast(target_type, expr) diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test index 87bb1aa946b4..895b16e5e3c3 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -57,6 +57,17 @@ cast(int, 1) [out] main:4: error: Redundant cast to "int" +[case testCastFromUnionOfAnyOk] +# flags: --warn-redundant-casts +from typing import Any, cast, Union + +x = Any +y = Any +z = Any + +def f(q: Union[x, y, z]) -> None: + cast(Union[x, y], q) + -- Unused 'type: ignore' comments -- ------------------------------