2

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?

  • 3
    `key = kwargs.get("key", "default")`? That's basically the whole _point_ of the `get` method. – jonrsharpe Apr 06 '21 at 08:49
  • Why is this even in kwargs? Why not just use the regular default argument mechanism? (You can make the argument keyword-only if you don't want it to be passed positionally.) – user2357112 Apr 06 '21 at 08:51
  • So I can just use `def foo(key="default")` instead? So what then is the point of `**kwargs` if I can just use that? – SomeoneLudo Apr 06 '21 at 08:53
  • Because in some cases you might want to accept arbitrary keyword arguments, it just doesn't seem like this is really one of them. – jonrsharpe Apr 06 '21 at 08:54
  • I don't understand what you mean by arbitary keyword arguments? Are you able to give an example? – SomeoneLudo Apr 06 '21 at 08:54
  • See e.g. https://stackoverflow.com/q/1769403/3001761. – jonrsharpe Apr 06 '21 at 08:57
  • 1
    For example, `dict` lets you do `dict(x=3, justinbieber=4)` and get `{'x': 3, 'justinbieber': 4}` even though it doesn't have arguments named `x` or `justinbieber` declared. If you want to do stuff like that, then *that's* what `**kwargs` is for. It has nothing to do with default values. – user2357112 Apr 06 '21 at 09:00
  • 1
    Wrt _"So I can just use `def foo(key="default")` instead?"_ - **Yes**. `kwargs` exists to allow a function to have arbitrary keyword arguments, like in user2357112-supports-Monica's example. If you know which keyword args you want/expect for your function, those should be in the function definition. For the rest, use `kwargs` - see jonrsharpe's linked question above. – aneroid Apr 06 '21 at 09:19
  • Does this answer your question? [Return None if Dictionary key is not available](https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available) – Tomerikoo Apr 06 '21 at 09:34

2 Answers2

3

Use default value of dict.get

def foo(**kwargs):
    key = kwargs.get("key", "default")
collinsuz
  • 439
  • 1
  • 4
  • 13
0

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)

pcko1
  • 833
  • 12
  • 22