How to use **kwargs to change a default value?

Viewed 919

I have a function (let's call it foo):

def foo(**kwargs):
    if kwargs.get("key") is not None:
        key = kwargs["key"]
    else:
        key = "default"

Here I have a default value for key but if kwargs has a value for key, I want to use that instead.

Is there a way to simplify this onto 1/2 lines?

2 Answers

Use default value of dict.get

def foo(**kwargs):
    key = kwargs.get("key", "default")

kwargs is essentialy of dict type. As such, the standard way (and the best-practise) of defaulting the value for a non-existent key is by using:

kwargs.get(key, default_val)

Related