Search code examples
pythondictionarykeyword-argument

In method call args, how to override keyword argument of unpacked dict?


I'm trying to use template keyword args for convenience in a function call (via dict and keyword arguments) whilst being able to override some arguments.

For example, if we start with a module mymod containing the line template_kvps = {'a': 1, 'b': 2}

I can just:

import mymod

def func(**kwargs):
    pass

func(**mymod.template_kvps)

then I can access my template_kvps within func(). But I want to be able to pass a different value for a with minimal overhead.

All I can think of is to alter the dictionary before the function call: kvps = {**template_kvps, 'a': 3}; func(**kvps), but that's twice the number of lines and I'm using this function several times in each of around 1000 test scripts.

I'd ideally like to redefine func so that I can do sth like func(**mymod.template_kvps, a=3) but as it is, Python errors with something about repeated parameters.

btw I'm happy to consider changing the format of the template_kvps.

EDIT (will move to answer at some point) I could use a wrapper method instead

def func_template(a=1, b=2):
    func(a, b)

func_template(a=3)

Solution

  • You can use the built-in dict type for that purpose. It accepts another dict as argument and additional key-value pairs as keyword arguments (which have precedence over the values in the other dict).

    Thus you can create an updated dictionary via dict(template_vars, a=1).

    You can unfold this dict as keyword arguments: func(**dict(...)).

    Like that there is no need to change the signature of your function and you can update/add as many key-value pairs as you want.