简体   繁体   中英

Defining default keyword values to function in a dictionary in python

I am writing a function that takes a lot of keywords.

I have a dictionary which is very lengthy that contains many of these keywords that already exists in my code and is being used elsewhere. Eg

{'setting1':None, 'setting2': None....}

I am wondering is there a way, when I define my function, for me to set all of these as keywords, rather than having to type them out again like this:

def my_function(setting1=None, setting2=None, **kwargs)

To be clear, essentially I want to set all of the contents of the dictionary to be keywords with default value None, and when I call the function I should be able to change their values. So I am not looking to provide the dictionary as kwargs upon calling the function.

While not exactly the same, I ususally prefer to save the arguments in **kwargs and use .get() to get the value or None :

def my_function(**kwargs):
     do_something(kwargs.get("alpha"), kwargs.get("beta"))

.get() on a dictionary returns the value if a key exists, or None of it does not. You can optionally specify a different default value as a second argument if you like.

When creating a function, you will need to implement how your arguments are used. By automatically creating arguments you end up adding arguments and forgetting to implement a behaviour for them.

# Manually defined.
def func(a, b, c, d):
    return a + b / c * d

# Auto-defined - Human error.
def func(""" auto define a,b,c,d,e,f,g,h """):
    return a + b / c * d # <- you only use half of the arguments. Confusing at best.

# Auto-defined - Inputs unclear, code is not explicit.
def func(defind_my_args):
    return a + b / c * d 

If you need to reuse "code behaviour" to the point that you can "inherit" parameters, maybe you should be using an object instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM