functools.partial in Python
In Python, functools.partial is a function within the functools module. This functions as a fundamental tool for encapsulating a callable object with default arguments. The outcome is a callable object, and we can treat it as if it were the original function. For instance, if a function requires two parameters, we can create a partial function from it, fixing the first parameter as an argument. Subsequently, we can call this partial function using only the other value as the parameter. This capability proves helpful in crafting modified versions of existing functions.
Syntax:
The signature for the partial function is as follows. This function returns a new partial object that, when called, behaves like a function with positional arguments as ‘args’ and keyword arguments as ‘keywords’. If additional arguments are passed to the call, they are appended to ‘args’. Similarly, if additional keyword arguments are provided, they extend and override the existing keywords.
partial(func,/,*args,*keywords)
Python partial function Examples:
Example 1:
In this scenario, we are calculating the multiplication of two numbers. Here, we observe the creation of a new function, mul2, which multiplies a value of 2 to the passed argument. Similarly, for mul9, it returns the result of the multiplication of the passed argument with 9.
from functools import partial
#Multiplication function
def multi(x,y):
return x*y
#partial functions
mul2 = partial(multi, y=2)
mul9 = partial(multi, 9)
print("2*5= ",mul2(5))
print("9*7 =",mul9(7))
Output:
2*5= 10
9*7 = 63
Example 2:
In this instance, we are utilizing the built-in pow() function from the math module. Consequently, it calculates 5 raised to the power specified in the parameter.
import math
import functools
p2=functools.partial(math.pow,5)
print(p2(2))
Output
125.0
Example 3:
In this case, we are calculating simple interest by passing the principal as a parameter while keeping the rate of interest and time fixed.
from functools import partial
def simpleint(p,r,t):
return (p*r*t)/100.0
si = partial(simpleint,7,t=3)
print("Simple interest is ",si(10000))
Output:
Simple interest is 2100.0
Conclusion:
Therefore, utilizing the partial function allows us to fix specific portions of a function’s arguments and/or keywords, creating a new object with a simplified signature.
References:
Happy Learning 🙂