Skip to content

Commit a6c0c64

Browse files
gh-59330: Improve error message for dest= for positionals (GH-125215)
Also improve the documentation. Specify how dest and metavar are derived from add_argument() positional arguments. Co-authored-by: Simon Law <[email protected]>
1 parent eb2d268 commit a6c0c64

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

Doc/library/argparse.rst

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,25 @@ be positional::
636636
usage: PROG [-h] [-f FOO] bar
637637
PROG: error: the following arguments are required: bar
638638

639+
By default, argparse automatically handles the internal naming and
640+
display names of arguments, simplifying the process without requiring
641+
additional configuration.
642+
As such, you do not need to specify the dest_ and metavar_ parameters.
643+
The dest_ parameter defaults to the argument name with underscores ``_``
644+
replacing hyphens ``-`` . The metavar_ parameter defaults to the
645+
upper-cased name. For example::
646+
647+
>>> parser = argparse.ArgumentParser(prog='PROG')
648+
>>> parser.add_argument('--foo-bar')
649+
>>> parser.parse_args(['--foo-bar', 'FOO-BAR']
650+
Namespace(foo_bar='FOO-BAR')
651+
>>> parser.print_help()
652+
usage: [-h] [--foo-bar FOO-BAR]
653+
654+
optional arguments:
655+
-h, --help show this help message and exit
656+
--foo-bar FOO-BAR
657+
639658

640659
.. _action:
641660

Lib/argparse.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1424,7 +1424,8 @@ def add_argument(self, *args, **kwargs):
14241424
chars = self.prefix_chars
14251425
if not args or len(args) == 1 and args[0][0] not in chars:
14261426
if args and 'dest' in kwargs:
1427-
raise ValueError('dest supplied twice for positional argument')
1427+
raise ValueError('dest supplied twice for positional argument,'
1428+
' did you mean metavar?')
14281429
kwargs = self._get_positional_kwargs(*args, **kwargs)
14291430

14301431
# otherwise, we're adding an optional argument

Lib/test/test_argparse.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5411,7 +5411,8 @@ def test_multiple_dest(self):
54115411
parser.add_argument(dest='foo')
54125412
with self.assertRaises(ValueError) as cm:
54135413
parser.add_argument('bar', dest='baz')
5414-
self.assertIn('dest supplied twice for positional argument',
5414+
self.assertIn('dest supplied twice for positional argument,'
5415+
' did you mean metavar?',
54155416
str(cm.exception))
54165417

54175418
def test_no_argument_actions(self):

0 commit comments

Comments
 (0)