11.2 Reducing with operator module functions
We’ll look at one more way that we can use the operator
module definitions: we can use them with the built-in functools.reduce()
function. The sum()
function, for example, can be implemented as follows:
sum = functools.partial(functools.reduce, operator.add)
This creates a partially evaluated version of the reduce()
function with the first argument supplied. In this case, it’s the +
operator, implemented via the operator.add()
function.
If we have a requirement for a similar function that computes a product, we can define it like this:
prod = functools.partial(functools.reduce, operator.mul)
This follows the pattern shown in the previous example. We have a partially evaluated reduce()
function with the first argument of the *
operator, as implemented by the operator.mul()
function.
It’s not clear whether we can do similar things with too many of the other operators. We might be able to find a use for the operator.concat...