Python’s functools module provides many useful features, one of which is the Partial function. It should be noted that the partial function here is not the same as the partial function in the mathematical sense.
When introducing function parameters, we mentioned that setting default values for parameters can reduce the difficulty of function calls. Partial functions can also achieve this. Here’s an example:
The int() function can convert a string to an integer. When only a string is passed in, the int() function converts it to a decimal number by default:
>>> int('12345')
12345
However, the int() function also provides an additional base parameter with a default value of 10. If the base parameter is provided, conversion between different number bases can be performed:
>>> int('12345', base=8)
5349
>>> int('12345', 16)
74565
Suppose we need to convert a large number of binary strings. It is very cumbersome to pass int(x, base=2) every time. Therefore, we can define a function int2() that passes base=2 by default:
def int2(x, base=2):
return int(x, base)
This makes converting binary numbers very convenient:
>>> int2('1000000')
64
>>> int2('1010101')
85
functools.partial helps us create such a partial function. Instead of defining int2() ourselves, we can directly use the following code to create a new function int2:
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
In short, the role of functools.partial is to fix certain parameters of a function (i.e., set default values), return a new function, and calling this new function will be simpler.
Note that the new int2 function above simply resets the default value of the base parameter to 2. However, you can still pass other values when calling the function:
>>> int2('1000000', base=10)
1000000
Finally, when creating a partial function, you can actually pass three types of arguments: a function object, *args, and **kw. When you write:
int2 = functools.partial(int, base=2)
You are effectively fixing the keyword argument base of the int() function. This means that:
int2('10010')
is equivalent to:
kw = { 'base': 2 }
int('10010', **kw)
When you write:
max2 = functools.partial(max, 10)
You are effectively adding 10 as part of the *args on the left. This means that:
max2(5, 6, 7)
is equivalent to:
args = (10, 5, 6, 7)
max(*args)
The result is 10.
do_partial.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import functools
int2 = functools.partial(int, base=2)
print("1000000 =", int2("1000000"))
print("1010101 =", int2("1010101"))
When a function has too many parameters and needs to be simplified, functools.partial can be used to create a new function. This new function can fix some parameters of the original function, making it simpler to call.