Optional self.args check

I am trying to extend some of the functionality of existing apps and in doing so I want to have optional args in the yaml definition.
I using the following to check if an arg, lights: ,exists in the yaml

if self.args[“lights”]:

but am receiving a KeyError when the code is run in the instance that the lights Args doesn’t exist. I would have thought if “lights:” doesn’t exist, then this would return false and would skip the code.

You have 2 options:

  • The first implies that the attribute lights has a default value and you coukd do the following:
self.args.get("lights", "the default value")
  • The second one would do something similar of what you would like:
if "lights" in self.args:
   # whatever you want to do

I would recommend you to use the first option since any optional attribute should always have a default value. If there is no value you want be assigned then you can pass None in the default parameter.

I hope it helps :slight_smile:

1 Like

Fully agree on @xaviml.

I prefer voluptuous to validate the configuration, saves me all the if xy in self.args, I did a short write up on voluptuous here in case you are interested.