Python partial functions are invoked by users through the functools module.
Partial Function Application
When a function is executed, it must be called with all necessary parameters. However, sometimes parameters can be known in advance before the function is called. In this case, one or more parameters of a function can be pre-set, so that the function can be called with fewer parameters.
A partial function takes the function to be carried as the first argument of the partial() function, and the original function's arguments are passed as subsequent arguments to partial(), unless keyword arguments are used.
A verbal description may not be enough to understand how partial functions are used, so let's illustrate with a common example. In this example, we implement a modulo function that, for the integer 100, obtains the remainder of 100%m for different values of m.
from functools import partial def mod( n, m ): return n % m mod_by_100 = partial( mod, 100 ) print mod( 100, 7 ) # 2 print mod_by_100( 7 ) # 2
Since the examples seen earlier generally use addition or multiplication, they fail to convey the positional issue of partial function arguments, which can easily create the false impression that partial's second argument is also the original function's second argument. So here I choose mod to explain.
In the case of keyword arguments, you don't need to follow the original function's argument positions or count. Let's look at another example below, which demonstrates how to perform conversions between different number bases.
from functools import partial bin2dec = partial( int, base=2 ) print bin2dec( '0b10001' ) # 17 print bin2dec( '10001' ) # 17 hex2dec = partial( int, base=16 ) print hex2dec( '0x67' ) # 103 print hex2dec( '67' ) # 103
These applications of partial functions may seem simple, but they are very useful. They can effectively follow the DRY principle and save programming costs.
Reprinted from Pythoner
Article link: http://www.pythoner.com/54.html