From c8c0bf920a6a527e6f7ed936260c743871c6a634 Mon Sep 17 00:00:00 2001 From: "steven.bethard" Date: Sat, 24 Oct 2009 19:47:15 +0000 Subject: Allow better custom type error messages using ArgumentTypeError. --- argparse.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'argparse.py') diff --git a/argparse.py b/argparse.py index 4f3edfb..bd03f29 100644 --- a/argparse.py +++ b/argparse.py @@ -722,6 +722,12 @@ class ArgumentError(Exception): return format % dict(message=self.message, argument_name=self.argument_name) + +class ArgumentTypeError(Exception): + """An error from trying to convert a command line string to a type.""" + pass + + # ============== # Action classes # ============== @@ -2191,7 +2197,13 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): try: result = type_func(arg_string) - # TypeErrors or ValueErrors indicate errors + # ArgumentTypeErrors indicate errors + except ArgumentTypeError: + name = getattr(action.type, '__name__', repr(action.type)) + msg = str(_sys.exc_info()[1]) + raise ArgumentError(action, msg) + + # TypeErrors or ValueErrors also indicate errors except (TypeError, ValueError): name = getattr(action.type, '__name__', repr(action.type)) msg = _('invalid %s value: %r') -- cgit v1.2.1