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.
After looking at argparse source code I figured out that it translates ArgumentTypeError to ArgumentError exception.
So instead of:
I should have:
And argparse would still do the rest for me (catch exception and print usage message) ...