Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,15 @@ def test_mutating_iteration(self):
for i in d:
d[i+1] = 1

def test_mutating_iteration_delete(self):
# change dict content during iteration
d = {}
d[0] = 0
with self.assertRaises(RuntimeError):
for i in d:
del d[0]
d[1] = 1

def test_mutating_lookup(self):
# changing dict during a lookup (issue #14417)
class NastyKey:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Changing `dict` keys during iteration will now be detected in certain corner cases where the number of keys isn't changed (but they keys themselves are), and a `RuntimeError` will be raised.
6 changes: 6 additions & 0 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3543,6 +3543,12 @@ dictiter_iternextkey(dictiterobject *di)
goto fail;
key = entry_ptr->me_key;
}
// We found an element (key), but did not expect it
if (di->len == 0) {
PyErr_SetString(PyExc_RuntimeError,
"dictionary keys changed during iteration");
goto fail;
}
di->di_pos = i+1;
di->len--;
Py_INCREF(key);
Expand Down