Partial Functions in Python

Partial function, as the name suggests allows us to fix the number of arguments in a function i.e partially fix the number of arguments to generate a new function.

We can create a different function by passing partial arguments in Python. We can fix some part of the arguments of the function which then results in a new object. In other words, we can create a function with some defaults.

Why do we need a partial function

When a function has multiple arguments, there might come a situation where some arguments take the same value each time while other arguments take different values each time. In a situation like this, we create a partial function, in which some of its arguments are fixed.

How to create a partial function in Python

Partial functions in Python can be created using the partial function from the functools library. For that, you must know how to create a Python function.

from functools import partial

#Create a function
def demo(a,b,c,d):
return a*b*c + d

#A partial function that calls demo with a as 1, b as 2 and c as 3
demo1= partial(demo,1,2,3)

#calling demo1()
print(demo1(2))

Output:

8

 

Example

In this example, we’ll calculate the interest amount using the Simple Interest formula.
Simple Interest = P*R*T/100
In this, we fix two arguments: the principal amount and rate of interest. Using a different value for time we can calculate the interest amount.

from functools import partial
#Create a function to calculate interest rate
def interest(Pr_amt, rate, time):
    interest_amt=(Pr_amt*rate*time)/100
    return interest_amt
#Create a partial function with principal amount 
#and rate of interest fixed    
abc= partial(interest,2000,5)
print("Interest amount:",abc(2))

Output:

Interest rate: 200.0

 

Uses of Python Partial functions

  1. They make the code re-usable by creating derived specialized functions.
  2. When the code is long it doesn’t make sense to re-write the code so partial functions are used.

Leave a Reply

Your email address will not be published. Required fields are marked *