Appearance
Partial Functions
The functools
module in Python provides many useful features, one of which is partial functions. Note that the term "partial function" here is different from its mathematical meaning.
When discussing function parameters, we mentioned that setting default parameter values can simplify function calls. Partial functions can also achieve this. Here’s an example:
The int()
function can convert a string to an integer. When only the string is passed in, the int()
function converts it to a decimal integer by default:
python
>>> int('12345')
12345
However, the int()
function also provides an additional base
parameter, which defaults to 10. If the base
parameter is passed in, it can perform conversions for other number systems:
python
>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565
Suppose we need to convert a large number of binary strings; passing int(x, base=2)
each time can be cumbersome. So, we might think about defining an int2()
function that defaults base
to 2:
python
def int2(x, base=2):
return int(x, base)
This makes converting binary numbers much more convenient:
python
>>> int2('1000000')
64
>>> int2('1010101')
85
functools.partial
helps us create a partial function, eliminating the need to define int2()
ourselves. We can directly use the following code to create a new function int2
:
python
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
To summarize, the role of functools.partial
is to fix some parameters of a function (i.e., set default values) and return a new function, making it easier to call.
Note that the new int2
function above simply resets the default value of the base
parameter to 2, but other values can still be passed in during the function call:
python
>>> int2('1000000', base=10)
1000000
Finally, when creating a partial function, it can actually accept three parameters: a function object, *args
, and **kw
. When passing in:
python
int2 = functools.partial(int, base=2)
It essentially fixes the keyword argument base
of the int()
function, equivalent to:
python
int2('10010')
which is equivalent to:
python
kw = { 'base': 2 }
int('10010', **kw)
When passing in:
python
max2 = functools.partial(max, 10)
It will automatically add 10 as part of *args
to the left, equivalent to:
python
max2(5, 6, 7)
which is equivalent to:
python
args = (10, 5, 6, 7)
max(*args)
The result will be 10.
Summary
When a function has too many parameters and needs to be simplified, using functools.partial
can create a new function that fixes some of the original function's parameters, making the function calls simpler.