0

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?

2
  • Do you mean you'd like to pass both a dict and kwargs at the same time? Like parDict.update({'group1.a': 4}, a=2, b=3)? Because the original method already supports that. Commented May 28, 2021 at 11:50
  • No, I want simply to do what I can do with parDict.update(). Either use tuples or a dictionary as arguments. Typically you need to switch from tuples to dictionary when the key is a string and not an identifier. Commented May 30, 2021 at 11:44

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.