]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-59330: Improve error message for dest= for positionals (GH-125215)
authorSerhiy Storchaka <storchaka@gmail.com>
Sat, 12 Oct 2024 11:46:28 +0000 (14:46 +0300)
committerGitHub <noreply@github.com>
Sat, 12 Oct 2024 11:46:28 +0000 (14:46 +0300)
Also improve the documentation. Specify how dest and metavar are derived
from add_argument() positional arguments.

Co-authored-by: Simon Law <sfllaw@sfllaw.ca>
Doc/library/argparse.rst
Lib/argparse.py
Lib/test/test_argparse.py

index d337de87ca8f396209cf8f0a16dc094af14bef1d..19f832051a9ee82bda39738c95b47739d72b795b 100644 (file)
@@ -636,6 +636,25 @@ be positional::
    usage: PROG [-h] [-f FOO] bar
    PROG: error: the following arguments are required: bar
 
+By default, argparse automatically handles the internal naming and
+display names of arguments, simplifying the process without requiring
+additional configuration.
+As such, 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:
 
index 208c1827f9aca75cd40068631411873a6f866363..64dbd7149e769c2c3dd0efcd54fe0ecdc5ff6e1b 100644 (file)
@@ -1424,7 +1424,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
index 000b810454f5849a2a241c60357ed0c93251baf0..61ddb5f16cc44f36c48ecb657bcbd7fda9ac9e18 100644 (file)
@@ -5411,7 +5411,8 @@ class TestInvalidArgumentConstructors(TestCase):
         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):