On Jul 12, 10:44 pm, Amir <[EMAIL PROTECTED]> 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) -- http://mail.python.org/mailman/listinfo/python-list