Creating a partial function
When we look at functions such as reduce()
, sorted()
, min()
, and max()
, we see that we'll often have some permanent argument values. For example, we might find a need to write something like this in several places:
reduce(operator.mul, ..., 1)
Of the three parameters to 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.
How can we define a function that has some parameters provided in advance?
Note that the goal here is different from providing default values. A partial function doesn't provide a way to override the defaults. Instead, we want to create as many partial functions as we need, each...