Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python counterpart to partial for ignoring an argument

Is there a "counterpart" in python for functools.partial?

Namely what I want to avoid is writing:

lambda x, y: f(x)

But I would love to preserve the same attributes (keyword-args, nice repr) as I do when I write:

from functools import partial
incr = partial(sum, 1)

instead of

incr = lambda x: sum(1, x)

I know that something like this is very easy to write, but I am wondering if there is already a standard way of ignoring arguments.

One common usecase of this would be Qts Signals and Slots.

like image 315
dreuter Avatar asked Oct 03 '15 11:10

dreuter


1 Answers

Just write a decorator that removes a certain number of arguments from the call:

def ignoreargs(func, count):
    @functools.wraps(func)
    def newfunc(*args, **kwargs):
        return func(*(args[count:]), **kwargs)
    return newfunc
>>> def test(a, b):
        print(a, b)
>>> test3 = ignoreargs(test, 3)
>>> test3(1, 2, 3, 4, 5)
4 5

my basic idea would be to make it more generic by default, e.g. having the signature: remap_args(f, mapping) where mapping is an iterable of ints which give you the position of the argument of the created function.

def remap_args(func, mapping):
    @functools.wraps(func)
    def newfunc(*args, **kwargs):
        newargs = [args[m] for m in mapping]
        return func(*newargs, **kwargs)
    return newfunc
>>> t = remap_args(test, [5, 2])
>>> t(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
5 2
like image 182
poke Avatar answered Sep 30 '22 05:09

poke