Take for example the python built in pow()
function.
xs = [1,2,3,4,5,6,7,8]
from functools import partial
list(map(partial(pow,2),xs))
>>> [2, 4, 8, 16, 32, 128, 256]
but how would I raise the xs to the power of 2?
to get [1, 4, 9, 16, 25, 49, 64]
list(map(partial(pow,y=2),xs))
TypeError: pow() takes no keyword arguments
I know list comprehensions would be easier.
Why not just create a quick lambda function which reorders the args and partial that
The very versatile funcy includes an
rpartial
function that exactly addresses this problem.It's just a lambda under the hood:
No
According to the documentation,
partial
cannot do this (emphasis my own):You could always just "fix"
pow
to have keyword args:You can do this with
lambda
, which is more flexible thanfunctools.partial()
:More generally:
One down-side of lambda is that some libraries are not able to serialize it.
One way of doing it would be:
but this involves re-defining the pow function.
if the use of partial was not 'needed' then a simple lambda would do the trick
And a specific way to map the pow of 2 would be
but none of these fully address the problem directly of partial applicaton in relation to keyword arguments
If you can't use lambda functions, you can also write a simple wrapper function that reorders the arguments.
and then call