The parser object itself saves some useful information we can use to check out the defaults we assigned when adding the argument.
Example script parser_ex.py
:
import argparse
def specified_nondefault(opts, parser, arg):
"""
Checks whether an argument was specified to be something other than the
default value.
..Note: This doesn't actually check if the argument was specified, as it
can be 'tricked' by the user specifying the default value.
:param argparse.Namespace opts: Parsed arguments to check.
:param argparse.Parser parser: The parser they were parsed with.
:param str arg: The name of the argument in question.
:return bool: Whether the current argument value differs from the default.
"""
if getattr(opts, arg) == parser.get_default(arg):
return False
return True
parser = argparse.ArgumentParser()
parser.add_argument('enabled_features', nargs='*', default=['A', 'B', 'C', 'D'])
opts = parser.parse_args()
print specified_nondefault(opts, parser, 'enabled_features')
In which case:
>> parser_ex.py 'B'
True
Because we've done something non-default. While
>> parser_ex.py 'A' 'B' 'C' 'D'
False
and
>> parser_ex.py
False
Since this just has default input.
Note that because we're checking against an entire list, there's some somewhat undesirable behaviour that order matters and
>> parser_ex.py 'B' 'A' 'C'
True
IMO, this is a problem with lumping all the features into a single argument, but you can certainly work around it one way or another if you care.
Then, if the user has/n't specified non-defualt enabled_features
, you can change them based on IP
as desired.