diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 4b7e39d2042a..0627391986ca 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4687,8 +4687,8 @@ 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 source_type == target_type + 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) 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..895b16e5e3c3 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -42,6 +42,32 @@ 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" + +[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 -- ------------------------------