This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author thomas.perl
Recipients thomas.perl
Date 2019-03-27.23:41:17
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1553730078.06.0.0762712838657.issue36452@roundup.psfhosted.org>
In-reply-to
Content
Using: Python 3.8 (git commit ID: d5a5a33f12b60129d57f9b423b77d2fcba506834), the following code snippet:

=====
a = {0: 0}

for i in a:
    del a[i]
    a[i+1] = 0
    print(i)
=====

Prints the following output:

=====
0
1
2
3
4
=====

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__())
=====
History
Date User Action Args
2019-03-27 23:41:18thomas.perlsetrecipients: + thomas.perl
2019-03-27 23:41:18thomas.perlsetmessageid: <1553730078.06.0.0762712838657.issue36452@roundup.psfhosted.org>
2019-03-27 23:41:18thomas.perllinkissue36452 messages
2019-03-27 23:41:17thomas.perlcreate