Imagine I have a function like
def foo(x):
...
When I call it with the dictionary { 'x': 42, 'y': 23 }
as keyword arguments I get an TypeError
:
>>> foo(**{ 'x': 42, 'y': 23 })
...
TypeError: foo() got an unexpected keyword argument 'y'
Is there a good way to make a function call with keyword arguments where additional keyword arguments are just ignored?
My solution so far: I can define a helper function:
import inspect
def call_with_kwargs(func, kwargs):
params = inspect.getargspec(func).args
return func(**{ k: v for k,v in kwargs.items() if k in params})
Now I can do
>>> call_with_kwargs(foo, { 'x': 42, 'y': 23 })
42
Is there a better way?
If altering your functions is fine, then just add a catch-all **kw
argument to it:
def foo(x, **kw):
# ...
and ignore whatever kw
captured in the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With