Search code examples
pythondictionarysyntaxfunction-call

How to make a function around dict.update() that similarly can take both positional and key-word args?


The built-in update function to dictionaries can take either, tuples or dictionaries as arguments. I want to make a function around it that also can take both tuples and dictionaries.

parDict = {}
parDict['a'] = 1
parDict['b'] = 2
parDict['group1.a'] = 3

I can do both:

parDict.update(a=2, b=3)
parDict.update({'group1.a':4})

Define a function

def par(**x):
    parDict.update(x)

I can do

par(a=2, b=3)

but I cannot do

par({'group1.a' : 4})

The error message is: par() takes 0 positional arguments but 1 was given

In my eyes {'group1.a' : 4} is a key-word argument (although 'group1.a' is not an identifier but a string. The same error text if I address the other parameter {'a': 4} which has an identifier.

If I in the function declaration change par(**x) to par(x) then I can do

par({'group1.a' : 4})

but not

par(a=2, b=3)

I can of course make an alias

par = parDict.update

This works for both types of arguments, but I want to do some more and really need a function here (to make some checks before update).

How should I improve the argument declaration, or the code, of par() to handle both types of arguments?


Solution

  • If i understand well, this would work for you:

    def par(*args, **kwargs):
        ## Merge positional and keyword arguments
        kwargs.update(*args)
        ## Do checks and stuff on kwargs before update
        # ....
        parDict.update(kwargs)