From c99a22a6bf4468a454ad950f634628e019e04a30 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Sun, 17 Apr 2022 21:20:39 -0700 Subject: [PATCH] Fix type context for cast() --- mypy/checkexpr.py | 2 +- test-data/unit/check-warnings.test | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 7383a2b69610..974a2144cd18 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3131,7 +3131,7 @@ def visit_enum_index_expr( def visit_cast_expr(self, expr: CastExpr) -> Type: """Type check a cast expression.""" - source_type = self.accept(expr.expr, type_context=AnyType(TypeOfAny.special_form), + source_type = self.accept(expr.expr, type_context=self.type_context[-1], allow_none_return=True, always_allow_any=True) target_type = expr.type options = self.chk.options diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test index 10c7968be475..398b3463a284 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -42,6 +42,15 @@ a: Any b = cast(Any, a) [builtins fixtures/list.pyi] +[case testRedundantCastTypeContext] +# flags: --warn-redundant-casts +from typing import List, cast + +class A: ... +class B(A): ... + +a: List[A] = cast(List[A], [B()]) # E: Redundant cast to "List[A]" + -- Unused 'type: ignore' comments -- ------------------------------