python - how to partially apply arbitrary argument of a function? -


i want use partial functools partially apply function's second argument, know easy lambda rather partial follows

>>> def func1(a,b): ...     return a/b ... >>> func2 = lambda x:func1(x,2) >>> func2(4) 2 

but strictly want use partial here (for sake of learning) came this.

>>> def swap_binary_args(func): ...     return lambda x,y: func(y,x) ... >>> func3 = partial(swap_binary_args(func1),2) >>> func3(4) 2 

is possible extend strategy level can partial apply arguments @ place in following pseudocode

>>>def indexed_partial(func, list_of_index, *args): ...     ###do_something### ...     return partially_applied_function  >>>func5=indexed_partial(func1, [1,4,3,5], 2,4,5,6) 

in our case can use function follows

>>>func6=indexed_partial(func1, [1], 2) 

is possible have indexed partial want ? there similar not aware of ? , more importantly idea of indexed partial or bad idea why ?

this question has been marked possible duplicate of can 1 partially apply second argument of function takes no keyword arguments? in question op asked possible partially apply second argument here asking how cook function can partially apply arbitrary argument

i, too, think ask can't done (easily?) functools.partial. best (and readable) solution use partial keyword-arguments. however, in case want use positional arguments (and hence indexed partial arguments), here possible definition of indexed_partial:

def indexed_partial(func, list_of_index, *args):     def partially_applied_function(*fargs, **fkwargs):         nargs = len(args) + len(fargs)         iargs = iter(args)         ifargs = iter(fargs)         posargs = ((ifargs, iargs)[i in list_of_index].next() in range(nargs))         return func(*posargs, **fkwargs)     return partially_applied_function 

Popular posts from this blog