From c4c0cf2bcc6d1329060c74b6d142cfec36f78022 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 7 Oct 2026 15:07:15 +0100 Subject: [PATCH 1/2] [mypyc] Fix evaluation order of multiple assignment from an iterable Fixes mypyc/mypyc#793. When unpacking an arbitrary iterable in a multiple assignment, mypyc interleaved getting items from the iterator and assigning them to the lvalues, and with a starred lvalue the items after the star were assigned in reverse order: ```python o.x, o.y = it # Was: o.x = next(it); o.y = next(it) ``` Python first gets all the items (and checks that the number of items is correct) before performing any assignments. Now mypyc does the same, and the lvalues are always assigned from left to right. This was already the case for lists and tuples. --- mypyc/irbuild/builder.py | 25 ++++++++------ mypyc/test-data/irbuild-statements.test | 38 +++++++++++----------- mypyc/test-data/run-misc.test | 43 +++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 28 deletions(-) diff --git a/mypyc/irbuild/builder.py b/mypyc/irbuild/builder.py index c81c1360ff8b8..a31e2d0548572 100644 --- a/mypyc/irbuild/builder.py +++ b/mypyc/irbuild/builder.py @@ -1033,8 +1033,11 @@ def process_iterator_tuple_assignment( # This may be the whole lvalue list if there is no starred value split_idx = target.star_idx if target.star_idx is not None else len(target.items) - # Assign values before the first starred value - for litem in target.items[:split_idx]: + # Get all the values before assigning anything, to match Python evaluation order + values = [] + + # Get values before the first starred value + for _ in range(split_idx): ritem = self.call_c(next_op, [iterator], line) error_block, ok_block = BasicBlock(), BasicBlock() self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR)) @@ -1049,9 +1052,9 @@ def process_iterator_tuple_assignment( self.activate_block(ok_block) - self.assign(litem, ritem, line) + values.append(ritem) - # Assign the starred value and all values after it + # Get the starred value and all values after it if target.star_idx is not None: post_star_vals = target.items[split_idx + 1 :] iter_list = self.primitive_op(to_list, [iterator], line) @@ -1072,12 +1075,11 @@ def process_iterator_tuple_assignment( self.activate_block(ok_block) - for litem in reversed(post_star_vals): - ritem = self.primitive_op(list_pop_last, [iter_list], line) - self.assign(litem, ritem, line) - - # Assign the starred value - self.assign(target.items[target.star_idx], iter_list, line) + post_star_values = [ + self.primitive_op(list_pop_last, [iter_list], line) for _ in post_star_vals + ] + values.append(iter_list) + values.extend(reversed(post_star_values)) # There is no starred value, so check if there are extra values in rhs that # have not been assigned. @@ -1096,6 +1098,9 @@ def process_iterator_tuple_assignment( self.activate_block(ok_block) + for litem, ritem in zip(target.items, values): + self.assign(litem, ritem, line) + def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None: self.nonlocal_control.append( LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block) diff --git a/mypyc/test-data/irbuild-statements.test b/mypyc/test-data/irbuild-statements.test index ccea1e8e746d7..b2bef7113d005 100644 --- a/mypyc/test-data/irbuild-statements.test +++ b/mypyc/test-data/irbuild-statements.test @@ -548,10 +548,11 @@ L0: def from_any(a): a, r0, r1 :: object r2 :: bool - x, r3 :: object + r3 :: object r4 :: bool - y, r5 :: object + r5 :: object r6 :: bool + x, y :: object L0: r0 = PyObject_GetIter(a) r1 = PyIter_Next(r0) @@ -560,20 +561,20 @@ L1: r2 = raise ValueError('not enough values to unpack') unreachable L2: - x = r1 r3 = PyIter_Next(r0) if is_error(r3) goto L3 else goto L4 L3: r4 = raise ValueError('not enough values to unpack') unreachable L4: - y = r3 r5 = PyIter_Next(r0) if is_error(r5) goto L6 else goto L5 L5: r6 = raise ValueError('too many values to unpack') unreachable L6: + x = r1 + y = r3 return 1 [case testMultiAssignmentCoercions] @@ -609,11 +610,12 @@ L0: def from_any(a): a, r0, r1 :: object r2 :: bool - r3, x :: int - r4 :: object - r5 :: bool - y, r6 :: object - r7 :: bool + r3 :: object + r4 :: bool + r5 :: object + r6 :: bool + r7, x :: int + y :: object L0: r0 = PyObject_GetIter(a) r1 = PyIter_Next(r0) @@ -622,21 +624,21 @@ L1: r2 = raise ValueError('not enough values to unpack') unreachable L2: - r3 = unbox(int, r1) - x = r3 - r4 = PyIter_Next(r0) - if is_error(r4) goto L3 else goto L4 + r3 = PyIter_Next(r0) + if is_error(r3) goto L3 else goto L4 L3: - r5 = raise ValueError('not enough values to unpack') + r4 = raise ValueError('not enough values to unpack') unreachable L4: - y = r4 - r6 = PyIter_Next(r0) - if is_error(r6) goto L6 else goto L5 + r5 = PyIter_Next(r0) + if is_error(r5) goto L6 else goto L5 L5: - r7 = raise ValueError('too many values to unpack') + r6 = raise ValueError('too many values to unpack') unreachable L6: + r7 = unbox(int, r1) + x = r7 + y = r3 return 1 [case testMultiAssignmentNested] diff --git a/mypyc/test-data/run-misc.test b/mypyc/test-data/run-misc.test index af0c53dd41d6e..d7a0b3354381c 100644 --- a/mypyc/test-data/run-misc.test +++ b/mypyc/test-data/run-misc.test @@ -467,6 +467,49 @@ with assertRaises(ValueError, "not enough values to unpack"): [out] +[case testUnpackIterableEvaluationOrder] +from typing import Any, Iterator + +from testutil import assertRaises + +log: list[str] = [] + +def gen(n: int) -> Iterator[int]: + for i in range(n): + log.append(f"next {i}") + yield i + log.append("end") + +class C: + def __setattr__(self, name: str, value: object) -> None: + log.append(f"set {name}={value}") + +def test_unpack_iterator_order() -> None: + log.clear() + c: Any = C() + c.x, c.y = gen(2) + assert log == ["next 0", "next 1", "end", "set x=0", "set y=1"], log + +def test_unpack_iterator_star_order() -> None: + log.clear() + c: Any = C() + c.x, *c.y, c.z, c.w = gen(5) + assert log == [ + "next 0", "next 1", "next 2", "next 3", "next 4", "end", + "set x=0", "set y=[1, 2]", "set z=3", "set w=4", + ], log + +def test_unpack_iterator_errors() -> None: + log.clear() + c: Any = C() + with assertRaises(ValueError, "too many values to unpack"): + c.x, c.y = gen(3) + with assertRaises(ValueError, "not enough values to unpack"): + c.x, c.y = gen(1) + with assertRaises(ValueError, "not enough values to unpack"): + c.x, *c.y, c.z = gen(1) + assert not any(s.startswith("set") for s in log), log + [case testModuleTopLevel] x = 1 print(x) From 9dd66a53d12ccd687ba35651a6923c2a2da006d0 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 30 Oct 2026 14:09:21 +0000 Subject: [PATCH 2/2] Merge test cases --- mypyc/test-data/run-misc.test | 131 +++++++++++++++------------------- 1 file changed, 59 insertions(+), 72 deletions(-) diff --git a/mypyc/test-data/run-misc.test b/mypyc/test-data/run-misc.test index d7a0b3354381c..f0aacf695eddc 100644 --- a/mypyc/test-data/run-misc.test +++ b/mypyc/test-data/run-misc.test @@ -342,7 +342,9 @@ bar 0 [case testMultipleAssignment] -from typing import Tuple, List, Any +from typing import Tuple, List, Any, Iterator + +from testutil import assertRaises def from_tuple(t: Tuple[int, str]) -> List[Any]: x, y = t @@ -369,40 +371,68 @@ def multiple_assignments(t: Tuple[int, str]) -> List[Any]: a, b = c, d = t e, f = g, h = 1, 2 return [a, b, c, d, e, f, g, h] -[file driver.py] -from native import ( - from_tuple, from_tuple_sequence, from_list, from_list_complex, from_any, multiple_assignments -) -assert from_tuple((1, 'x')) == ['x', 1] +def test_from_tuple() -> None: + assert from_tuple((1, 'x')) == ['x', 1] -assert from_tuple_sequence((1, 5, 4)) == [4, 5, 1] -try: - from_tuple_sequence((1, 5)) -except ValueError as e: - assert 'not enough values to unpack (expected 3, got 2)' in str(e) -else: - assert False +def test_from_tuple_sequence() -> None: + assert from_tuple_sequence((1, 5, 4)) == [4, 5, 1] + with assertRaises(ValueError, "not enough values to unpack (expected 3, got 2)"): + from_tuple_sequence((1, 5)) -assert from_list([3, 4]) == [4, 3] -try: - from_list([5, 4, 3]) -except ValueError as e: - assert 'too many values to unpack (expected 2)' in str(e) -else: - assert False +def test_from_list() -> None: + assert from_list([3, 4]) == [4, 3] + with assertRaises(ValueError, "too many values to unpack (expected 2)"): + from_list([5, 4, 3]) -assert from_list_complex([7, 6]) == [6, 7] -try: - from_list_complex([5, 4, 3]) -except ValueError as e: - assert 'too many values to unpack (expected 2)' in str(e) -else: - assert False +def test_from_list_complex() -> None: + assert from_list_complex([7, 6]) == [6, 7] + with assertRaises(ValueError, "too many values to unpack (expected 2)"): + from_list_complex([5, 4, 3]) + +def test_from_any() -> None: + assert from_any('xy') == ['y', 'x'] + +def test_multiple_assignments() -> None: + assert multiple_assignments((4, 'x')) == [4, 'x', 4, 'x', 1, 2, 1, 2] + +log: list[str] = [] + +def gen(n: int) -> Iterator[int]: + for i in range(n): + log.append(f"next {i}") + yield i + log.append("end") + +class C: + def __setattr__(self, name: str, value: object) -> None: + log.append(f"set {name}={value}") -assert from_any('xy') == ['y', 'x'] +def test_unpack_iterator_order() -> None: + log.clear() + c: Any = C() + c.x, c.y = gen(2) + assert log == ["next 0", "next 1", "end", "set x=0", "set y=1"], log + +def test_unpack_iterator_star_order() -> None: + log.clear() + c: Any = C() + c.x, *c.y, c.z, c.w = gen(5) + assert log == [ + "next 0", "next 1", "next 2", "next 3", "next 4", "end", + "set x=0", "set y=[1, 2]", "set z=3", "set w=4", + ], log -assert multiple_assignments((4, 'x')) == [4, 'x', 4, 'x', 1, 2, 1, 2] +def test_unpack_iterator_errors() -> None: + log.clear() + c: Any = C() + with assertRaises(ValueError, "too many values to unpack"): + c.x, c.y = gen(3) + with assertRaises(ValueError, "not enough values to unpack"): + c.x, c.y = gen(1) + with assertRaises(ValueError, "not enough values to unpack"): + c.x, *c.y, c.z = gen(1) + assert not any(s.startswith("set") for s in log), log [case testUnpack] from typing import List @@ -467,49 +497,6 @@ with assertRaises(ValueError, "not enough values to unpack"): [out] -[case testUnpackIterableEvaluationOrder] -from typing import Any, Iterator - -from testutil import assertRaises - -log: list[str] = [] - -def gen(n: int) -> Iterator[int]: - for i in range(n): - log.append(f"next {i}") - yield i - log.append("end") - -class C: - def __setattr__(self, name: str, value: object) -> None: - log.append(f"set {name}={value}") - -def test_unpack_iterator_order() -> None: - log.clear() - c: Any = C() - c.x, c.y = gen(2) - assert log == ["next 0", "next 1", "end", "set x=0", "set y=1"], log - -def test_unpack_iterator_star_order() -> None: - log.clear() - c: Any = C() - c.x, *c.y, c.z, c.w = gen(5) - assert log == [ - "next 0", "next 1", "next 2", "next 3", "next 4", "end", - "set x=0", "set y=[1, 2]", "set z=3", "set w=4", - ], log - -def test_unpack_iterator_errors() -> None: - log.clear() - c: Any = C() - with assertRaises(ValueError, "too many values to unpack"): - c.x, c.y = gen(3) - with assertRaises(ValueError, "not enough values to unpack"): - c.x, c.y = gen(1) - with assertRaises(ValueError, "not enough values to unpack"): - c.x, *c.y, c.z = gen(1) - assert not any(s.startswith("set") for s in log), log - [case testModuleTopLevel] x = 1 print(x)