Skip to content

gh-137921: Mark map/accumulate iterators exhausted when the user callback raises… #137936

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

Conversation

PrathmeshAdsod
Copy link

#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.

@python-cla-bot
Copy link

python-cla-bot bot commented Aug 19, 2025

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app
Copy link

bedevere-app bot commented Aug 19, 2025

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@StanFromIreland
Copy link
Member

StanFromIreland commented Aug 19, 2025

The attached issue is currently pending, which means it may face closure soon. I recommend you wait till the discussion is resolved.

This PR will need a blurb.

@picnixz
Copy link
Member

picnixz commented Aug 19, 2025

We don't want to fix it because this is how it is meant to be. Please don't create PRs that are not needed. In addition changes to builtins likely require a PEP (this wouldn't be the only built-in that would need to be changed if we were to do this).

@picnixz picnixz closed this Aug 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants