5

Basically imagine that I have argparser that has multiple arguments. I have a particular function definition that looks like this:

    def add_to_parser(self, parser):
        group = parser.add_argument_group('')
        group.add_argument( '--deprecateThis', action='throw exception', help='Stop using this. this is deprecated')

Whether I can try and create that action to throw an exception and stop the code or if I can wrap it to check for the deprecateThis flag and then throw an exception, I'd like to know how to do it and which is best! Thanks.

Joseph Song
  • 184
  • 1
  • 12
  • 2
    You could provide a `type` function that throws an error if anything is supplied to it. Or yes, just check after the parsing if there's anything in that argument. – jonrsharpe Nov 16 '16 at 22:24
  • but what if I want to have "action=throwexception" or something? Where would I be providing the type function to do so? Thanks for the fast response! – Joseph Song Nov 16 '16 at 22:47
  • 2
    No, there are [predefined actions](https://docs.python.org/3/library/argparse.html#action). Demo of using `type`: http://stackoverflow.com/a/25470943/3001761 – jonrsharpe Nov 16 '16 at 22:50
  • That works! Thanks a lot @jonrsharpe :) If you wanna answer it, i'll give you the check! – Joseph Song Nov 16 '16 at 22:56

1 Answers1

2

Here's what I came up with:

You can register custom actions for your arguments, I registered one to print out a deprecation warning and remove the item from the resulting namespace:

class DeprecateAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        self.call_count = 0
        if 'help' in kwargs:
            kwargs['help'] = f'[DEPRECATED] {kwargs["help"]}'
        super().__init__(*args, **kwargs)


    def __call__(self, parser, namespace, values, option_string=None):
        if self.call_count == 0:
            sys.stderr.write(f"The option `{option_string}` is deprecated. It will be ignored.\n")
            sys.stderr.write(self.help + '\n')
            delattr(namespace, self.dest)
        self.call_count += 1


if __name__ == "__main__":
    my_parser = ArgumentParser('this is the description')
    my_parser.register('action', 'ignore', DeprecateAction)
    my_parser.add_argument(
        '-f', '--foo', 
        help="This argument is deprecated", 
        action='ignore')

    args = my_parser.parse_args()
    # print(args.foo)  # <- would throw an exception
Ibolit
  • 9,218
  • 7
  • 52
  • 96