SomeoneLudo
SomeoneLudo

Reputation: 55

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

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?

Upvotes: 2

Views: 3364

Answers (2)

collinsuz
collinsuz

Reputation: 459

Use default value of dict.get

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

Upvotes: 4

pcko1
pcko1

Reputation: 981

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)

Upvotes: 0

Related Questions