Creating a partial function
When we look at functions such as reduce()
, sorted()
, min()
, and max()
, we see that we'll often have some argument values that change very rarely, if at all. In a particular context, they're essentially fixed. For example, we might find a need to write something like this in several places:
reduce(operator.mul, ..., 1)
Of the three parameters for reduce()
, only one – the iterable to process – actually changes. The operator and the base value arguments are essentially fixed at operator.mul
and 1
.
Clearly, we can define a whole new function for this:
def prod(iterable):
return reduce(operator.mul, iterable, 1)
However, Python has a few ways to simplify this pattern so that we don't have to repeat the boilerplate def
and return
statements.
The goal of this recipe is different from providing general default values. A partial function doesn't provide a way for us to override the defaults...