We know a partial function is an original function for particular argument values. Basic syntax of partial function is,
partial(func[, *args][, **keywords])
Now, let's assume a particular program.
from functools import partial
def power(a, b):
return a ** b
pw = partial(power, b=4)
print('Default keywords for pw :', pw.keywords)
print('Default arguments for pw :', pw.args)
print('Answer of pw is: ',pw(3))
# Output
# -------
# Default keywords for pw: {'b': 4}
# Default arguments for pw: ()
# Answer of pw is: 81
The output is correct and the above partial function i set keywords as b=4
and default agrs
is ()
. Now, if I omit the keyword b
and that place i put only 4. The scenario is changed to answer is 64.
partial(power, 4)
# Output
# -------
# Default keywords for pw: {}
# Default arguments for pw: (4,)
# Answer of pw is: 64
My question is why args and keywords get interchanged when I don't want to pass b
since though in the first case I didn't pass a
but the result was correct.
You are providing 4
as a positional argument, and those are applied strictly from left to right when calling the partial
instance. That is, partial(f, 4)
is roughly the equivalent of lambda x: pow(4, x)
. There is no way to define an equivalent of the function lambda x: pow(x, 4)
with partial
without using keyword arguments.