Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what if the key in kwargs has conflict with the function keyword

in a function like

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

if the named parameters I've passed in has a keyword "a" already, the call will failed.

Currently I need to call myfunc with a dictionary from other place (so I can't control the content of the dictionary), like

myfunc(1,2, **dict)

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

if there any way to write a decorator to solve this problem since this may be a common problem ?

like image 679
Jerrylk Avatar asked Oct 24 '25 00:10

Jerrylk


2 Answers

If your function is taking a an actual dict from somewhere else, you don't need to pass it using **. Just pass the dict like a normal argument:

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

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

You only need to use **kwargs if myfunc is designed to take an arbitrary number of keyword arguments. Like this:

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

If you're just passing it a dict, it's not needed.

like image 97
dano Avatar answered Oct 25 '25 15:10

dano


If this is seriously an issue, don't name your arguments. Just use splat arguments:

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

and parse args manually.

like image 42
nneonneo Avatar answered Oct 25 '25 14:10

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!