]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-113008: Correct argparse usage output for required, mutually exclusive groups...
authorPayton <72841140+paytonward6@users.noreply.github.com>
Tue, 24 Sep 2024 14:14:35 +0000 (09:14 -0500)
committerGitHub <noreply@github.com>
Tue, 24 Sep 2024 14:14:35 +0000 (17:14 +0300)
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2023-12-14-13-43-27.gh-issue-113008.jWYn8T.rst [new file with mode: 0644]

index 66192fb92832a24eec5123f70a848507ebc36833..694c46db61d1779aff037ab9fb04572c7f0b550e 100644 (file)
@@ -395,12 +395,12 @@ class HelpFormatter(object):
                 continue
 
             try:
-                start = actions.index(group._group_actions[0])
+                start = min(actions.index(item) for item in group._group_actions)
             except ValueError:
                 continue
             else:
                 end = start + len(group._group_actions)
-                if actions[start:end] == group._group_actions:
+                if set(actions[start:end]) == set(group._group_actions):
                     group_actions.update(group._group_actions)
                     inserts[start, end] = group
 
index c6b7698694097726ab440039b1cec830644f98f9..ef05a6fefcffcce431553478d00f3980013f70d8 100644 (file)
@@ -2902,6 +2902,29 @@ class TestMutuallyExclusiveGroupErrors(TestCase):
               '''
         self.assertEqual(parser.format_help(), textwrap.dedent(expected))
 
+    def test_optional_order(self):
+        parser = ErrorRaisingArgumentParser(prog='PROG')
+        group = parser.add_mutually_exclusive_group(required=True)
+        group.add_argument('--foo')
+        group.add_argument('bar', nargs='?')
+        expected = '''\
+            usage: PROG [-h] (--foo FOO | bar)
+
+            positional arguments:
+              bar
+
+            options:
+              -h, --help  show this help message and exit
+              --foo FOO
+              '''
+        self.assertEqual(parser.format_help(), textwrap.dedent(expected))
+
+        parser = ErrorRaisingArgumentParser(prog='PROG')
+        group = parser.add_mutually_exclusive_group(required=True)
+        group.add_argument('bar', nargs='?')
+        group.add_argument('--foo')
+        self.assertEqual(parser.format_help(), textwrap.dedent(expected))
+
     def test_help_subparser_all_mutually_exclusive_group_members_suppressed(self):
         self.maxDiff = None
         parser = ErrorRaisingArgumentParser(prog='PROG')
diff --git a/Misc/NEWS.d/next/Library/2023-12-14-13-43-27.gh-issue-113008.jWYn8T.rst b/Misc/NEWS.d/next/Library/2023-12-14-13-43-27.gh-issue-113008.jWYn8T.rst
new file mode 100644 (file)
index 0000000..0f2a442
--- /dev/null
@@ -0,0 +1 @@
+Correct argparse usage output for required, mutually exclusive groups containing a positional argument