diff options
author | steven.bethard <devnull@localhost> | 2009-10-24 19:47:15 +0000 |
---|---|---|
committer | steven.bethard <devnull@localhost> | 2009-10-24 19:47:15 +0000 |
commit | c8c0bf920a6a527e6f7ed936260c743871c6a634 (patch) | |
tree | 39b29222b428a2199cc555b53c80200f1df74ed8 /argparse.py | |
parent | c24b8c04f07fc5abbb1d9bc44ea4e0bdc013a631 (diff) | |
download | argparse-c8c0bf920a6a527e6f7ed936260c743871c6a634.tar.gz |
Allow better custom type error messages using ArgumentTypeError.
Diffstat (limited to 'argparse.py')
-rw-r--r-- | argparse.py | 14 |
1 files changed, 13 insertions, 1 deletions
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') |