functools
moduleThe 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.
partial
methodThe 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.
functools.partial(func, /, *args, **keywords)
func
: This is the function name.*args
: These are positional arguments.**keywords
: These are keyword arguments.This method returns a partial object that is callable.
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)
The sub
method from the operator module takes two arguments (x, y)
and returns the difference, x - y
.
partial
method from the functools
module and import the sub
method from the operator
module.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.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
.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
.partial()
on a user-defined functionLet'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)
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
.