Skip to content

Instantly share code, notes, and snippets.

@thorsummoner
Created April 22, 2016 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thorsummoner/9850b5d6cd5e6bb5a3b9b7792b69b0a5 to your computer and use it in GitHub Desktop.
Save thorsummoner/9850b5d6cd5e6bb5a3b9b7792b69b0a5 to your computer and use it in GitHub Desktop.
argparse with --no-flag options
import argparse
class ActionFlagWithNo(argparse.Action):
"""
Allows a 'no' prefix to disable store_true actions.
For example, --debug will have an additional --no-debug to explicitly disable it.
"""
def __init__(self, opt_name, dest=None, default=True, required=False, help=None):
super(ActionFlagWithNo, self).__init__(
[
'--' + opt_name[0],
'--no-' + opt_name[0],
] + opt_name[1:],
dest=(opt_name[0].replace('-', '_') if dest is None else dest),
nargs=0, const=None, default=default, required=required, help=help,
)
def __call__(self, parser, namespace, values, option_string=None):
if option_string.startswith('--no-'):
setattr(namespace, self.dest, False)
else:
setattr(namespace, self.dest, True)
class ActionFlagWithNoFormatter(argparse.HelpFormatter):
"""
This changes the --help output, what is originally this:
--file, --no-file, -f
Will be condensed like this:
--[no-]file, -f
"""
def _format_action_invocation(self, action):
if action.option_strings[1].startswith('--no-'):
return ', '.join(
[action.option_strings[0][:2] + '[no-]' + action.option_strings[0][2:]]
+ action.option_strings[2:]
)
return super(ActionFlagWithNoFormatter, self)._format_action_invocation(action)
def main(argp=None):
if argp is None:
argp = argparse.ArgumentParser(
formatter_class=ActionFlagWithNoFormatter,
)
argp._add_action(ActionFlagWithNo(['flaga', '-a'], default=False, help='...'))
argp._add_action(ActionFlagWithNo(['flabb', '-b'], default=False, help='...'))
argp = argp.parse_args()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment