Hi Pythonistas
Today we are going to learn a very simple but interesting topic which is a partial function.Partial functions allow us to set certain arguments to function and create a new function.
Let's see this with an example
from functools import partial
def multiply(a, b):
return a * b
doubler = partial(multiply, 2)
print(doubler)
print(doubler(5))
tripler = partial(multiply, 3)
print(tripler(5))
functools.partial(<function multiply at 0x7f5c6161b1f0>, 2)
10
15
In this example, there is a multiply function that takes 2 arguments and returns the product of two arguments
doubler = partial(multiply, 2)
This makes a new function with one argument set as two. So doubler needs only one argument and returns double the input argument
Partial functions help us to create multiple variants of functions without duplicating the code.
Hope you have learned something from this post. Please share your suggestion with afsal@parseltongue.co.in