7

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?

Stephan Kulla
  • 4,739
  • 3
  • 26
  • 35

1 Answers1

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343