Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching ArgumentTypeError exception from custom action

What is the best practice to throw an ArgumentTypeError exception from my own custom action and let the argparse to catch it for me?

It seems that argparse's try/except block does not handle this exception for my custom actions. Though it does that just fine for its built-in actions.

class unique_server_endpoints(argparse.Action):
    """This class avoids having two duplicate OuterIPs in the client argument list"""
    def __call__(self, parser, namespace, values, option_string=None):
        ips = set()
        endpoints = []
        for r in values:
            ep = server_endpoint(r)
            if ep[0] in ips:
                raise argparse.ArgumentTypeError("Duplicate OuterIPs found")
            else:
                ips.add(ep[0])
                endpoints.append(ep)
        setattr(namespace, self.dest, endpoints)

and

group.add_argument('-c', "--client", nargs = 2,
            dest = "servers", action = unique_server_endpoints,

For example, in the code above If I would have duplicate IPs then the exception would fall down to the main function and print the ugly stacktrace. I don't want that and neither I don't want to put a try/except block inside main.

like image 214
user389238 Avatar asked Mar 27 '12 00:03

user389238


1 Answers

After looking at argparse source code I figured out that it translates ArgumentTypeError to ArgumentError exception.

So instead of:

            raise argparse.ArgumentTypeError("Duplicate OuterIPs found")

I should have:

            raise argparse.ArgumentError(self, "Duplicate OuterIPs found")

And argparse would still do the rest for me (catch exception and print usage message) ...

like image 83
user389238 Avatar answered Oct 13 '22 21:10

user389238