0

With keyword arguments, you can't just reference potential keyword values in the dict, since they may not be present. What's the best way to reference keyword values that may or may not be there? I find myself doing things like this:

def save_link(link, user, **kwargs):

    if "auto" in kwargs:
        auto = kwargs["auto"]
    else:
        auto = False

in order to provide default values and create a variable that is reliably present. Is there a better way?

Laizer
  • 5,932
  • 7
  • 46
  • 73

1 Answers1

6

You may use the get property of dict:

auto = kwargs.get('auto', False)

This allows for using a default value (Falsein this case).

However, please be quite careful with this approach, because this kind of code does not complain about wrong keyword arguments. Someone calls funct(1,2,auot=True) and everything looks ok. You might consider checking that the kwargs you receive belong to some certain list.

DrV
  • 22,637
  • 7
  • 60
  • 72