Skip to content

Commit 5b0b7f9

Browse files
authored
Check list multiplication operands in evaluation order (#22263)
Check the list first, using the outer context because list repetition preserves the item type (this code path doesn't look at rmul), and let the operator checker handle the multiplier. Also the code path works for SupportsIndex now Authored by Codex
1 parent 62dad9a commit 5b0b7f9

2 files changed

Lines changed: 7 additions & 7 deletions

File tree

‎mypy/checkexpr.py‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4537,13 +4537,7 @@ def check_list_multiply(self, e: OpExpr) -> Type:
45374537
45384538
Type inference is special-cased for this common construct.
45394539
"""
4540-
right_type = self.accept(e.right)
4541-
if is_subtype(right_type, self.named_type("builtins.int")):
4542-
# Special case: [...] * <int value>. Use the type context of the
4543-
# OpExpr, since the multiplication does not affect the type.
4544-
left_type = self.accept(e.left, type_context=self.type_context[-1])
4545-
else:
4546-
left_type = self.accept(e.left)
4540+
left_type = self.accept(e.left, type_context=self.type_context[-1])
45474541
result, method_type = self.check_op("__mul__", left_type, e.right, e)
45484542
e.method_type = method_type
45494543
return result

‎test-data/unit/check-inference-context.test‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,12 @@ a: List[int]
847847
if int():
848848
a = [None] * 3 # E: List item 0 has incompatible type "None"; expected "int"
849849
a = [''] * 3 # E: List item 0 has incompatible type "str"; expected "int"
850+
851+
def walrus(n: int | None) -> None:
852+
a: List[int] = [n] * (n := 1) # E: List item 0 has incompatible type "int | None"; expected "int"
853+
n = None
854+
b: List[object] = [(n := 1)] * n
855+
reveal_type(n) # N: Revealed type is "builtins.int"
850856
[builtins fixtures/list.pyi]
851857

852858
[case testUnionTypeContext]

0 commit comments

Comments
 (0)