Search code examples
python-3.xdictionarykeyword-argumentargument-unpacking

How to remove/ignore unexpected keyword arguments when passing as dictionary?


The following code

def f(par1, par2):
    print("par1 = %s, par2 = %s" % (str(par1), str(par2)))

pars = {
    'par1': 12,
    'par2': 13,
    'par3': 14
}

f(**pars)

raises error

TypeError: f() got an unexpected keyword argument 'par3'

How to either ignore par3 or find, that it is unexpected and pop it from dictionary programmtically?


Solution

  • You can get functions arguments with __code__.co_varnames

    expected = {key: pars[key] for key in f.__code__.co_varnames}
    f(**expected)