The smallest change would be to use
args.value = values.get(args.values)
so you would get None for any entry not in the dict (eg default).
Another option is to misuse the type keyword of argparse:
values = { "on": True, "off": False, "switch": None }
def convertvalues(value):
return values.get(value)
parser.add_argument('-v','--value',type=convertvalues)
The "type" approach breaks the use of choices as used above, since choices is applied after the conversion. One possibility to preserve your use of choices would be:
def convertvalues(value):
return values.get(value,value)
parser.add_argument('-v','--value',type=convertvalues,
choices=[True,False,None],
default=None)
In this case convertvalues returns the right values if 'on','off','switch' and None are used and returns the given values if something else was given (eg. 'bla'). Since 'bla' is not in choices, you get the expected error message.
Using "action" with a class derived from argparse.Action instead of type should do the job the smart way, as given in the docs:
class DictAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
value_dict = { "on": True, "off": False, "switch": None }
setattr(namespace, self.dest, value_dict.get(values))
parser.add_argument('-v','--value',action=DictAction,
choices=['on','off','switch'],
default=None)
Of course this is not perfect, a better solution would overwrite the Acion init to get the dictionary and leave out the hardcoded value_dict.