filtering keyword arguments

bukzor workitharder at gmail.com
Sun Jul 13 08:04:23 CEST 2008


On Jul 12, 8:44 pm, Amir <amirn... at gmail.com> wrote:
> How do you filter keyword arguments before passing them to a function?
>
> For example:
>
> def f(x=1): return x
>
> def g(a, **kwargs): print a, f(**kwargs)
>
> In [5]: g(1, x=3)
> 1 3
>
> In [6]: g(1, x=3, y=4)
> TypeError: f() got an unexpected keyword argument 'y'
>
> Is there a way to do something like:
>
> def g(a, **kwargs): print a, f(filter_rules(f, **kwargs))
>
> so only {'x': 3} is passed to f?
>
> I was hoping for a pythonic way of doing what in Mathematica is done
> by FilterRules:
>
> http://reference.wolfram.com/mathematica/ref/FilterRules.html

Here it is as a decorator:


def filter_arguments(func):
    def func2(*args, **kwargs):
        import inspect
        arglist, vararg, kwarg, defaults = inspect.getargspec(func)
        for k in kwargs.copy():
            if k not in arglist: del kwargs[k]
        return func(*args, **kwargs)
    return func2


@filter_arguments
def func(a=1, b=2): return a+b


print func()
print func(c=3)
print func(a=3,b=4)



More information about the Python-list mailing list