Created
April 22, 2016 21:09
-
-
Save thorsummoner/9850b5d6cd5e6bb5a3b9b7792b69b0a5 to your computer and use it in GitHub Desktop.
argparse with --no-flag options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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