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 partialfrom operator import subpartial_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
partialmethod from thefunctoolsmodule and import thesubmethod from theoperatormodule. - Line 4: We create a partial function of the
subfunction by freezing the first argument,x, to always have the value of3. The partial function is named,partial_sub. Therefore, when we usepartial_suband pass an argument to it, the argument is considered the second argument,y, for thesubfunction. - Line 6: We invoke
partial_subwith5as the argument. This is equivalent tosub(x=3,y=5). Hence, the value returned is-2. This means3-5. - Line 10: We invoke
partial_subwith1as the argument. This is equivalent tosub(x=3,y=1). Therefore, the value returned is2. This means3-1.
The partial() on a user-defined function
Let's view another code example of the partial()method:
from functools import partialfrom sre_parse import fix_flagsdef 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.