Freezing all but one positional argument

What is a good way to define a function partial_k(f, k, args)that takes an arbitrary function fas input ( ftakes npositional arguments), a value k and a list of values n-1and returns a new function that freezes all arguments fexcept the kth argument?

For example:

def f(a, b, c):
    return (a, b, c)

assert partial_k(f, 2, [0, 1])(10) == (0, 1, 10) # lambda x: (0, 1, x)
assert partial_k(f, 1, [0, 1])(10) == (0, 10, 1) # lambda x: (0, x, 1)

I could only find very verbose ways to do this.

+4
source share
2 answers

You can use the wrapper function and pass arguments before and after the kith element, using slicing to the original function f:

def partial_k(f, k, seq):
    seq = tuple(seq)  # To handle any iterable
    def wrapper(x):
        return f(*(seq[:k] + (x,) + seq[k:]))
    return wrapper

print(partial_k(f, 2, [0, 1])(10))
print(partial_k(f, 1, [0, 1])(10))

Output:

(0, 1, 10)
(0, 10, 1)

For Python 3.5+:

def partial_k(f, k, seq):
    def wrapper(x):
        return f(*seq[:k], x, *seq[k:])
    return wrapper
+3

, functools , :

def make_partial(f, args, k):

    def func(x):
        new_args = args[:k] + [x] + args[k:]
        return f(*new_args)

    return func
+1

Source: https://habr.com/ru/post/1610184/


All Articles