filtering keyword arguments

Peter Otten __peter__ at web.de
Sun Jul 13 01:32:22 EDT 2008


Amir 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 think you have to come up with something yourself. Here's a start:

import inspect

def filter_kw(f, **kw):
    names = inspect.getargspec(f)[0]
    return dict((n, kw[n]) for n in names if n in kw)

Peter



More information about the Python-list mailing list