[Python-ideas] Add nullifier argument to functools.reduce?

Joshua Landau joshua at landau.ws
Sat Aug 23 18:01:20 CEST 2014


On 23 August 2014 16:30, Warren Weckesser <warren.weckesser at gmail.com> wrote:
> I'd like to add an additional optional argument to functools.reduce.
> The argument is the "nullifier" of the reducing operation.  It is a value
> such that function(nullifier, anything) returns nullifier.  For example, if
> function(x, y) computes x*y, the nullifier is 0.  If function(x, y) is
> the intersection of the sets x and y, the nullifier is the empty set.
>
> The argument would allow reduce to "short circuit" its calculation.   When
> reduce encounters the nullifier, it can return immediately.  This can
> provide
> a significant improvement in performance in some cases.

This hasn't been given a use-case and seems like needless complexity.
It also seems far too magical. -1 for those reasons.

If its only purpose is to speed up "reduce" it seems like a very bad
trade-off, as *everywhere else* has a new now-sanctioned behaviour to
worry about.

A better answer in my opinion would be something more like
"reduce(..., stop_on=sentinel)". This could even allow more
optimisations than your idea:

    reduce(operator.mul, iterable, stop_on=0)
    reduce(operator.add, iterable, stop_on=float("nan"))

etc.

I would be -0 on that, because there hasn't been a mentioned use-case.


More information about the Python-ideas mailing list