Skip to content

gh-161004: Fixed functools.reduce where it calls iter() twice - #161015

Closed
NotorandXor256 wants to merge 8 commits into
python:mainfrom
NotorandXor256:fix/functools.reduce
Closed

NotorandXor256 wants to merge 8 commits into
python:mainfrom
NotorandXor256:fix/functools.reduce

Conversation

@NotorandXor256

@NotorandXor256 NotorandXor256 commented Oct 31, 2026 •

Copy link
Copy Markdown

Fixes #161004
This PR fix functools.reduce.The C functools_reduce calls PyObject_GetIter(seq) once and then only PyIter_Next(it). The Python version calls iter(sequence) and then for element in it:, which calls iter() again on the iterator.

this PR fix this behavior by change for loop for element in it: to while loop. While loop is terminated next(element) throw a StopIteration exception and error handle it and break the loop

this PR also add a test and change the documentation

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35547167 | 📁 Comparing 587dcc4 against main (663e99d)

  🔍 Preview build  

3 files changed
± library/functools.html
± library/os.path.html
± whatsnew/changelog.html

@picnixz picnixz closed this Oct 31, 2026
@picnixz

picnixz commented Oct 31, 2026

Copy link
Copy Markdown
Member

You have lots of unrelated changes. I suggest you open a new PR without those un-necssary changes from other PRs

@picnixz

picnixz commented Oct 31, 2026

Copy link
Copy Markdown
Member

(checkout from a fresh main that is not tainted by commits not in origin/main)

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.

Pure-Python functools.reduce calls iter() twice, unlike the C implementation

2 participants