Skip to content

Commit ddb543d

Browse files
committed
Set index to -1 when list iterators become exhausted in tier 2
1 parent 59be79a commit ddb543d

File tree

5 files changed

+23
-6
lines changed

5 files changed

+23
-6
lines changed

Lib/test/test_list.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,15 @@ def __eq__(self, other):
299299
lst = [X(), X()]
300300
X() in lst
301301

302+
def test_tier2_invalidates_iterator(self):
303+
# GH-121012
304+
for _ in range(100):
305+
a = [1, 2, 3]
306+
it = iter(a)
307+
for _ in it:
308+
pass
309+
a.append(4)
310+
self.assertEqual(list(it), [])
302311

303312
if __name__ == "__main__":
304313
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Tier 2 execution now ensures that list iterators remain exhausted, once they
2+
become exhausted.

Python/bytecodes.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2975,9 +2975,11 @@ dummy_func(
29752975
_PyListIterObject *it = (_PyListIterObject *)iter_o;
29762976
assert(Py_TYPE(iter_o) == &PyListIter_Type);
29772977
PyListObject *seq = it->it_seq;
2978+
Py_ssize_t index = it->it_index;
29782979
assert(seq);
2979-
assert(it->it_index < PyList_GET_SIZE(seq));
2980-
next = PyStackRef_FromPyObjectNew(PyList_GET_ITEM(seq, it->it_index++));
2980+
assert(index < PyList_GET_SIZE(seq));
2981+
next = PyStackRef_FromPyObjectNew(PyList_GET_ITEM(seq, index));
2982+
it->it_index = index + 1 == PyList_GET_SIZE(seq) ? -1 : index + 1;
29812983
}
29822984

29832985
macro(FOR_ITER_LIST) =

Python/executor_cases.c.h

Lines changed: 4 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Python/generated_cases.c.h

Lines changed: 4 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)