What is the partial() method in the Python functools module?

The functools module

The functools module in Python creates higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the scope of the function without modifying or explicitly defining them.

The partial method

The partial() method simplifies the function signature by freezing certain arguments of the passed function. It returns a partial object that behaves like the passed function.

Syntax


functools.partial(func, /, *args, **keywords)

Parameters

  • func: This is the function name.
  • *args: These are positional arguments.
  • **keywords: These are keyword arguments.

Return value

This method returns a partial object that is callable.

Example

from functools import partial
from operator import sub
partial_sub = partial(sub, 3)
diff1 = partial_sub(5)
print("partial_sub(5) -", diff1)
diff2 = partial_sub(1)
print("partial_sub(1) -", diff2)

Explanation

The sub method from the operator module takes two arguments (x, y) and returns the difference, x - y.

  • Lines 1-2: We import the partial method from the functools module and import the sub method from the operator module.
  • Line 4: We create a partial function of the sub function by freezing the first argument, x, to always have the value of 3. The partial function is named, partial_sub. Therefore, when we use partial_sub and pass an argument to it, the argument is considered the second argument, y, for the sub function.
  • Line 6: We invoke partial_sub with 5 as the argument. This is equivalent to sub(x=3,y=5). Hence, the value returned is -2. This means 3-5.
  • Line 10: We invoke partial_sub with 1 as the argument. This is equivalent to sub(x=3,y=1). Therefore, the value returned is 2. This means 3-1.

The partial() on a user-defined function

Let's view another code example of the partial()method:

from functools import partial
from sre_parse import fix_flags
def myFunc(arg1, arg2):
print("arg1 = %s, arg2 = %s " % (arg1, arg2))
fixed_arg1 = "hi"
partial_myFunc = partial(myFunc, fixed_arg1)
arg2 = "educative"
partial_myFunc(arg2)
arg2 = "edpresso"
partial_myFunc(arg2)

Explanation

In the code above, we define a user-defined function called myFunc that takes two arguments, arg1 and arg2. We fix/freeze the first argument, arg1, to be hi using the partial function on myFunc. We use the partial object, partial_myFunc, to pass different values for arg1 and arg2.

Free Resources