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.
As already said that's a limitation of
functools.partial
if the function you want topartial
doesn't accept keyword arguments.If you don't mind using an external library 1 you could use
iteration_utilities.partial
which has a partial that supports placeholders:1 Disclaimer: I'm the author of the
iteration_utilities
library (installation instructions can be found in the documentation in case you're interested).I think I'd just use this simple one-liner:
Update:
I also came up with a funnier than useful solution. It's a beautiful syntactic sugar, profiting from the fact that the
...
literal meansEllipsis
in Python3. It's a modified version ofpartial
, allowing to omit some positional arguments between the leftmost and rightmost ones. The only drawback is that you can't pass anymore Ellipsis as argument.So the the solution for the original question would be with this version of partial
list(map(partial(pow, ..., 2),xs))
you could use a closure
You could create a helper function for this:
Disclaimer: I haven't tested this with keyword arguments so it might blow up because of them somehow. Also I'm not sure if this is what
@wraps
should be used for but it seemed right -ish.