gh-137921: Mark map/accumulate iterators exhausted when the user callback raises… #137936
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
#137921
This PR is created to solve the bug discussed in the above issue.
Summary ->
The built-in map() function and itertools.accumulate() would produce "broken" iterators if the user-provided callback function raised a StopIteration. According to the Python iterator protocol, once an iterator raises StopIteration, it must continue to do so on all subsequent calls. However, the existing implementation would only stop the iteration temporarily. If another attempt was made to get the next item, the iterator would incorrectly resume, yielding more items from the underlying sequence. This violated the fundamental contract of how iterators should behave. (according to the doc and discussion in the issue)
Summary of the Solution
The fix ensures that both map and itertools.accumulate iterators correctly and permanently exhaust after the callback raises StopIteration. This was achieved by introducing a finished flag to the internal state of each iterator object.
When a StopIteration is caught from the user's callback, this flag is set to true. On any subsequent call to retrieve the next item, the iterator first checks this flag. If it is set, the iterator immediately stops, thus upholding the iterator protocol.