From 7fc676eb6d70220b6b104932bce474f6ba07067e Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Wed, 21 Oct 2026 13:04:55 -0700 Subject: [PATCH] Check list multiplication operands in evaluation order Check the list first, using the outer context because list repetition preserves the item type, and let the operator checker handle the multiplier. Authored by Codex --- mypy/checkexpr.py | 8 +------- test-data/unit/check-inference-context.test | 6 ++++++ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 52a3affa81a94..b30e39c172bd2 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4536,13 +4536,7 @@ def check_list_multiply(self, e: OpExpr) -> Type: Type inference is special-cased for this common construct. """ - right_type = self.accept(e.right) - if is_subtype(right_type, self.named_type("builtins.int")): - # Special case: [...] * . Use the type context of the - # OpExpr, since the multiplication does not affect the type. - left_type = self.accept(e.left, type_context=self.type_context[-1]) - else: - left_type = self.accept(e.left) + left_type = self.accept(e.left, type_context=self.type_context[-1]) result, method_type = self.check_op("__mul__", left_type, e.right, e) e.method_type = method_type return result diff --git a/test-data/unit/check-inference-context.test b/test-data/unit/check-inference-context.test index 3735f0183eb4a..dbbee77b8b32c 100644 --- a/test-data/unit/check-inference-context.test +++ b/test-data/unit/check-inference-context.test @@ -847,6 +847,12 @@ a: List[int] if int(): a = [None] * 3 # E: List item 0 has incompatible type "None"; expected "int" a = [''] * 3 # E: List item 0 has incompatible type "str"; expected "int" + +def walrus(n: int | None) -> None: + a: List[int] = [n] * (n := 1) # E: List item 0 has incompatible type "int | None"; expected "int" + n = None + b: List[object] = [(n := 1)] * n + reveal_type(n) # N: Revealed type is "builtins.int" [builtins fixtures/list.pyi] [case testUnionTypeContext]