Skip to content

Commit

Permalink
pythongh-59330: Improve error message for dest= for positionals
Browse files Browse the repository at this point in the history
Also improve the documentation. Specify how dest and metavar are derived
from add_argument() positional arguments.

Co-authored-by: Simon Law <[email protected]>
  • Loading branch information
serhiy-storchaka and sfllaw committed Oct 9, 2024
1 parent f2cb399 commit 3e64528
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
16 changes: 16 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,22 @@ be positional::
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar

You do not need to specify the dest_ and metavar_ parameters. 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:

Expand Down
3 changes: 2 additions & 1 deletion Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,8 @@ def add_argument(self, *args, **kwargs):
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
Expand Down
3 changes: 2 additions & 1 deletion Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5338,7 +5338,8 @@ def test_multiple_dest(self):
parser.add_argument(dest='foo')
with self.assertRaises(ValueError) as cm:
parser.add_argument('bar', dest='baz')
self.assertIn('dest supplied twice for positional argument',
self.assertIn('dest supplied twice for positional argument,'
' did you mean metavar?',
str(cm.exception))

def test_no_argument_actions(self):
Expand Down

0 comments on commit 3e64528

Please sign in to comment.