Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore additional keyword arguments in python [duplicate]

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?

like image 803
Stephan Kulla Avatar asked Apr 16 '15 16:04

Stephan Kulla


1 Answers

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.

like image 128
Martijn Pieters Avatar answered Oct 20 '22 07:10

Martijn Pieters