user2304916
user2304916

Reputation: 8124

Python: Passing and updating default parameters idoms

If I wrap a function into a bigger function but I still want to have access to all the parameters of the inner function is customary to do:

def bigFun(par1, **kwargs):
    innerFun(**kwargs)

Now, if I want to provide default values in the wrapper function and still have let the user to override these value I can do:

def bigFun(par1, **kwargs):
    default_kwargs = dict(keyX=valueX, keyY=valueY, ...)
    default_kwargs.update(**kwargs)
    kwargs = default_kwargs
    innerFun(**kwargs)

which I don't particularly like.

It seems a common enough situation to me.

Any other idiom do people use in this case?

Upvotes: 3

Views: 100

Answers (3)

barracel
barracel

Reputation: 1829

You could use setdefault

def bigFun(par1, **kwargs):
    kwargs.setdefault(keyX, valueX)
    kwargs.setdefault(keyY, valueY)
    innerFun(**kwargs)

Upvotes: 1

astrognocci
astrognocci

Reputation: 1085

You could use the keyword notation in your wrapper function for default, and pass them explicitely to the inner one:

def bigFun(arg, def_arg='foo', other_arg='bar', **kwargs):
    innerFun(def_arg=def_arg, other_arg=other_arg, **kwargs)

Upvotes: 2

perreal
perreal

Reputation: 97948

def bigFun(par1, **kwargs):
    kwargs[keyX] = kwargs.get(keyX, valueX)
    innerFun(**kwargs)

or for multiple pairs:

def bigFun(par1, **kwargs):
    for k,v in [('key1', 'val1'), ('key2', 'val2')]:
        kwargs[k] = kwargs.get(k, v)
    innerFun(**kwargs)

Upvotes: 2

Related Questions