Two things in this patch: The first is a documentation change that describes how ``dest`` and ``metavar`` parameters behave by default, in the "name or flags" section. The second is a change in exception behaviour. If you write: >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('foo-bar', dest='foo_bar') You will get an exception that tells you about the ``metavar`` option, which beginners may not have noticed. diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -655,6 +655,22 @@ be positional:: usage: PROG [-h] [-f FOO] bar PROG: error: too few arguments +You do not need to specify the dest_ and metavar_ parameters for +an optional argument. the dest_ parameter defaults to the argument +name with underscores ``_`` replacing hyphens ``-`` . The metavar_ +parameter defaults to the upper-cased name. For example:: + + >>> parser = argparse.ArgumentParser(prog='PROG') + >>> parser.add_argument('--foo-bar') + >>> parser.parse_args(['--foo-bar', 'FOO-BAR'] + Namespace(foo_bar='FOO-BAR') + >>> parser.print_help() + usage: [-h] [--foo-bar FOO-BAR] + + optional arguments: + -h, --help show this help message and exit + --foo-bar FOO-BAR + action ^^^^^^ diff --git a/Lib/argparse.py b/Lib/argparse.py --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1259,7 +1259,8 @@ class _ActionsContainer(object): chars = self.prefix_chars if not args or len(args) == 1 and args[0][0] not in chars: if args and 'dest' in kwargs: - raise ValueError('dest supplied twice for positional argument') + raise ValueError('dest supplied twice for positional argument,' + ' did you mean metavar?') kwargs = self._get_positional_kwargs(*args, **kwargs) # otherwise, we're adding an optional argument diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -4072,7 +4072,8 @@ class TestInvalidArgumentConstructors(Te parser.add_argument('bar', dest='baz') except ValueError: e = sys.exc_info()[1] - expected = 'dest supplied twice for positional argument' + expected = ('dest supplied twice for positional argument,' + ' did you mean metavar?') msg = 'expected %r, found %r' % (expected, e) self.assertTrue(expected in str(e), msg)