In this tutorial, we will learn partial functions and their usage in Python.
What is Partial function?
A partial function in programming is a function that is defined for only a subset of possible inputs. It allows you to specify a fixed number of arguments in advance, leaving some arguments to be provided later. This can be useful for creating reusable and flexible code.
In Python, we can use the functools’ partial function to implement the partial function.The functools is a module in Python’s standard library that provides higher-order functions and operations on callable objects.
Let’s understand with an example, suppose we have a function to multiply two numbers.
def multiply(first_num, second_num): '''Multiply two numbers''' return first_num * second_num
We can convert the multiply function to calculate the double of a number using partial function.
from functools import partial double = partial(multiply,second_num=2)
Here one argument to multiply function is fixed(2), the partial function double can accept one number. Now we can call the function double :
We can also add docstring to the partial function using the __doc__ dunder function.
from functools import partial double = partial(multiply,second_num=2) double.__doc__ = "Calcualte double of the number"
Suppose we have a function to calculate the power of a number.
def power(number,exponent): return number ** exponent
We can define a square and cube partial functions as shown below :
square = partial(power,exponent=2) cube = partial(power,exponent=3)
We can call cube partial function :
When to use Partial functions
Partial functions are usable in the following contexts :
- When you need to fix one or more arguments of a function and create a new function with reduced arity(The term “arity” refers to the number of arguments or parameters that a function or operation can accept).
- We want to create a function with default arguments.
- When you need to pass a function as an argument to another function with specific arguments already set.
- When we want reusable code