Skip to content

[mypyc] Fix for loop iteration when the loop body reassigns the iterable - #22137

Merged
p-sawicki merged 1 commit into
python:masterfrom
rheard:fix-mypyc-1233
Oct 22, 2026
Merged

p-sawicki merged 1 commit into
python:masterfrom
rheard:fix-mypyc-1233

Conversation

@rheard

@rheard rheard commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1233

for loops over lists, tuples, strings, bytes, dicts and range() (also inside enumerate(), zip() and reversed()) read the iterable, or the end of the range, on every iteration. When it was a local variable, the loop read the variable's register, so assigning to the variable in the loop body changed the iteration: for i in range(n): n = 0 ran once, for x in a: a = [9] stopped after the first item, and a loop over a tuple read past the end of the new tuple, which could segfault.

Now, if the loop target or body assigns to the local variable that holds the iterable or the end of the range, its value is copied to a new register before the loop. A small AST visitor finds these assignments: plain, augmented and starred assignments, :=, del, for targets, with ... as, except ... as and match capture patterns. Other loops generate the same IR as before. Copying unconditionally would add a copy to every loop over a local variable and change the IR of 23 existing test cases.

The comprehension form, [x for x in t if (t := (9,))], is fixed separately by #22133.

@rheard
rheard force-pushed the fix-mypyc-1233 branch 2 times, most recently from 14781dc to 6d72db2 Compare October 16, 2026 20:58

@p-sawicki p-sawicki left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

@p-sawicki
p-sawicki merged commit 1107984 into python:master Oct 22, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reassigning the iterated variable inside a for loop changes the iteration (segfault for tuples)

2 participants