filtering keyword arguments

alex.gaynor at gmail.com alex.gaynor at gmail.com
Sun Jul 13 01:33:20 EDT 2008


On Jul 12, 10: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

Sure, you could do:

def call_with_relevant_args(func, kwargs):
    kwargs = dict([(k, v) for k, v in kwargs.iteritems() if k in
func.func_code.co_varnames])
    return func(**kwargs)



More information about the Python-list mailing list