python / cpython

The Python programming language
https://www.python.org
Other
63.38k stars 30.35k forks source link

Allow `functools.reduce`s 'initial' to be a keyword argument #125916

Open sayandipdutta opened 2 weeks ago

sayandipdutta commented 2 weeks ago

Feature or enhancement

Proposal:

functools.reduce takes function (generally a callable) and iterable, with an optional initial parameter:

https://docs.python.org/3/library/functools.html#functools.reduce

However, initial cannot be passed as a keyword argument, which reduces ;) readability,

from functools import reduce
from operator import sub
>>> reduce(sub, [1, 1, 2, 3, 5, 8], 21)
1
>>> reduce(sub, [1, 1, 2, 3, 5, 8], initial=21)
TypeError: reduce() takes no keyword arguments

Allowing initial as keyword argument will be more clear, and initial could also be passed as a keyword argument while making partial functions out of reduce.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/remove-positional-only-restriction-on-initial-parameter-of-reduce/68897

Linked PRs

skirpichev commented 2 weeks ago

See also https://github.com/python/cpython/pull/121677

skirpichev commented 2 weeks ago

Also see #96640.

@sobolevn, did you actually try to do conversion and benchmark it?