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

前端 未结 10 1655
太阳男子
太阳男子 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:27

    You could create a helper function for this:

    from functools import wraps
    def foo(a, b, c, d, e):
        print('foo(a={}, b={}, c={}, d={}, e={})'.format(a, b, c, d, e))
    
    def partial_at(func, index, value):
        @wraps(func)
        def result(*rest, **kwargs):
            args = []
            args.extend(rest[:index])
            args.append(value)
            args.extend(rest[index:])
            return func(*args, **kwargs)
        return result
    
    if __name__ == '__main__':
        bar = partial_at(foo, 2, 'C')
        bar('A', 'B', 'D', 'E') 
        # Prints: foo(a=A, b=B, c=C, d=D, e=E)
    

    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.

提交回复
热议问题