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

前端 未结 10 1684
太阳男子
太阳男子 2020-11-28 06:45

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))

>&g         


        
10条回答
  •  天涯浪人
    2020-11-28 07:26

    As already said that's a limitation of functools.partial if the function you want to partial 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:

    >>> from iteration_utilities import partial
    >>> square = partial(pow, partial._, 2)  # the partial._ attribute represents a placeholder
    >>> list(map(square, xs))
    [1, 4, 9, 16, 25, 36, 49, 64]
    

    1 Disclaimer: I'm the author of the iteration_utilities library (installation instructions can be found in the documentation in case you're interested).

提交回复
热议问题