pythonargumentspartial-application

Can one partially apply the second argument of a function that takes no keyword arguments?


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.


Solution

  • No

    According to the documentation, partial cannot do this (emphasis my own):

    partial.args

    The leftmost positional arguments that will be prepended to the positional arguments


    You could always just "fix" pow to have keyword args:

    _pow = pow
    pow = lambda x, y: _pow(x, y)