1

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?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

4

You can get functions arguments with __code__.co_varnames

expected = {key: pars[key] for key in f.__code__.co_varnames}
f(**expected)
kaidokuuppa
  • 642
  • 4
  • 10
4

You could define your function to accept keyword arguments like:

def f(par1, par2, **kwargs):
    print("par1 = %s, par2 = %s" % (str(par1), str(par2)))
Mohammad Mustaqeem
  • 1,034
  • 5
  • 9