From 2625b0a678d70589259af957452404a34822a19f Mon Sep 17 00:00:00 2001 From: lau0708 Date: Sun, 22 Nov 2026 21:29:39 +0800 Subject: [PATCH 1/2] Check cast operands without an Any type context Passing AnyType(special_form) as the type context suppressed inference of type variables from the operand's own arguments, so e.g. cast(tuple[A, A], f(A)) checked f(A) in a context of Any and inferred tuple[A, Any]. The redundant-cast check therefore compared tuple[A, Any] with tuple[A, A] and stayed silent. Checking the operand with no type context keeps the inference local to the operand and lets --warn-redundant-casts report such casts (fixes #22509). --- mypy/checkexpr.py | 2 +- test-data/unit/check-warnings.test | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85e..902dcaee9f4ae 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -5037,7 +5037,7 @@ 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), + type_context=None, allow_none_return=True, always_allow_any=True, ) diff --git a/test-data/unit/check-warnings.test b/test-data/unit/check-warnings.test index 8ab1f398ba429..1a8abe6894298 100644 --- a/test-data/unit/check-warnings.test +++ b/test-data/unit/check-warnings.test @@ -282,3 +282,16 @@ def identity(xs: list[T]) -> list[T]: def f(xs: list[int]) -> list[int]: return cast(list[int], identity(xs)) # E: Redundant cast to "list[int]" + +[case testRedundantCastGenericCallWithTuple] +# flags: --warn-redundant-casts +from typing import Callable, TypeVar, cast + +T = TypeVar("T") + +class A: ... + +def f(factory: Callable[[], T]) -> tuple[A, T]: ... + +cast(tuple[A, A], f(A)) # E: Redundant cast to "tuple[A, A]" +[builtins fixtures/tuple.pyi] From d9e19d36d32e181927de02e6889eeb8ff03e9447 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:31:35 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- mypy/checkexpr.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 902dcaee9f4ae..a6cf1cab64701 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -5036,10 +5036,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=None, - allow_none_return=True, - always_allow_any=True, + expr.expr, type_context=None, allow_none_return=True, always_allow_any=True ) target_type = expr.type options = self.chk.options