diff -r 8630fa732cf6 Lib/argparse.py --- a/Lib/argparse.py Thu Jan 17 17:07:17 2013 +0100 +++ b/Lib/argparse.py Fri Jan 18 15:46:44 2013 +0100 @@ -582,7 +582,10 @@ elif action.nargs == PARSER: result = '%s ...' % get_metavar(1) else: - formats = ['%s' for _ in range(action.nargs)] + try: + formats = ['%s' for _ in range(action.nargs)] + except TypeError: + raise ValueError("invalid nargs value") result = ' '.join(formats) % get_metavar(action.nargs) return result @@ -834,7 +837,7 @@ help=None, metavar=None): if nargs == 0: - raise ValueError('nargs for store actions must be > 0; if you ' + raise ValueError('nargs for store actions must be != 0; if you ' 'have nothing to store, actions such as store ' 'true or store const may be more appropriate') if const is not None and nargs != OPTIONAL: @@ -926,7 +929,7 @@ help=None, metavar=None): if nargs == 0: - raise ValueError('nargs for append actions must be > 0; if arg ' + raise ValueError('nargs for append actions must be != 0; if arg ' 'strings are not supplying the value to append, ' 'the append const action may be more appropriate') if const is not None and nargs != OPTIONAL: diff -r 8630fa732cf6 Lib/test/test_argparse.py --- a/Lib/test/test_argparse.py Thu Jan 17 17:07:17 2013 +0100 +++ b/Lib/test/test_argparse.py Fri Jan 18 15:46:44 2013 +0100 @@ -4089,7 +4089,6 @@ class TestHelpMetavarTypeFormatter(HelpTestCase): - """""" def custom_type(string): return string @@ -4885,6 +4884,35 @@ def test_nargs_3_metavar_length3(self): self.do_test_no_exception(nargs=3, metavar=("1", "2", "3")) + +class TestInvalidNargs(TestCase): + + EXPECTED_INVALID_MESSAGE = "invalid nargs value" + EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you " + "have nothing to store, actions such as store " + "true or store const may be more appropriate") + + def do_test_range_exception(self, nargs): + parser = argparse.ArgumentParser() + with self.assertRaises(ValueError) as cm: + parser.add_argument("--foo", nargs=nargs) + self.assertEqual(cm.exception.args[0], self.EXPECTED_RANGE_MESSAGE) + + def do_test_invalid_exception(self, nargs): + parser = argparse.ArgumentParser() + with self.assertRaises(ValueError) as cm: + parser.add_argument("--foo", nargs=nargs) + self.assertEqual(cm.exception.args[0], self.EXPECTED_INVALID_MESSAGE) + + # Unit tests for different values of nargs + + def test_nargs_alphabetic(self): + self.do_test_invalid_exception(nargs='a') + self.do_test_invalid_exception(nargs="abcd") + + def test_nargs_zero(self): + self.do_test_range_exception(nargs=0) + # ============================ # from argparse import * tests # ============================