What if a key in kwargs conflicts with a function keyword

in a function like

def myfunc(a, b, **kwargs):
    do someting

      

if the named parameters I passed already have the "a" keyword, the call will fail.

Currently I need to call myfunc with a dictionary from somewhere else (so I cannot manage the contents of the dictionary), for example

myfunc(1,2, **dict)

      

how to make sure there is no conflict? if so, what is the solution?

if there is a way to write a decorator to solve this problem, so how could this be a common problem?

+3


source to share


3 answers


If this is serious, don't provide your arguments. Just use splat arguments:

def myfunc(*args, **kwargs):
    ...

      



and disassemble by args

hand.

+2


source


If your function accepts an actual dict from elsewhere, then you don't need to pass it using **

. Just pass the dict as a regular argument:

def myfunc(a, b, kwargs):
    # do something

myfunc(1,2, dct) # No ** needed

      

You need to use **kwargs

if myfunc

designed to accept an arbitrary number of keyword arguments. Like this:



myfunc(1,2, a=3, b=5, something=5)

      

If you just pass a dict to it, it is not needed.

+3


source


2 things:

  • if myfunc(1,2, **otherdict)

    called from somewhere else where you have no control over that in otherdict

    - you can't do anything, they call your function incorrectly. The caller must ensure that there are no conflicts.

  • if you are the caller ... then you just need to combine the dictates themselves. i.e:.

x

otherdict = some_called_function()`
# My values should take precedence over what in the dict
otherdict.update(a=1, b=2)
# OR i am just supplying defaults in case they didn't
otherdict.setdefault('a', 1)
otherdict.setdefault('b', 2)
# In either case, then i just use kwargs only.
myfunc(**otherdict)

      

0


source







All Articles