-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Detect dict iteration "overflow" when changing keys #80633
Comments
Using: Python 3.8 (git commit ID: d5a5a33), the following code snippet: ===== a = {0: 0}
for i in a:
del a[i]
a[i+1] = 0
print(i) ===== Prints the following output: ===== The reason for this seems to be the way the internal key list is managed and the "next" value in this list is retrieved. The amount of items seems to be related to USABLE_FRACTION(PyDict_MINSIZE). Since cases where the dictionary size changes are detected with a RuntimeError, I would expect the invariant to be "the number of iterations is the len() of the dict at the time the iterator is created to be enforced. Whether to raise a StopIteration instead or raising a RuntimeError is up for debate. Attached is a patch that tries to detect this corner case and raise a RuntimeError instead (plus a unit test). Note also that without the patch, the __length_hint__() of the iterator actually underflows: ===== a = {0: 0}
it = iter(a)
print('Length hint:', it.__length_hint__())
next(it)
print('Length hint:', it.__length_hint__())
del a[0]
a[1] = 0
next(it)
print('Length hint:', it.__length_hint__()) ===== |
Thank you. I like your patch. |
…or while modifying the keys of dict during iteration. probably this issue: python/cpython#80633
…or while modifying the keys of dict during iteration. (#976) probably this issue: python/cpython#80633
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: