]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-26952: [argparse] clearer error when formatting an empty mutually… (GH-30099...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 15 Dec 2021 12:24:48 +0000 (04:24 -0800)
committerGitHub <noreply@github.com>
Wed, 15 Dec 2021 12:24:48 +0000 (12:24 +0000)
(cherry picked from commit 86de99588db3beff964137f4fe27dd1077a09b35)

Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst [new file with mode: 0644]

index 7c28547f3e522c68b9f9a24058c36b2ef6f8ee85..40569437ac62b6155ec5e19d518ce20b6436790f 100644 (file)
@@ -392,6 +392,9 @@ class HelpFormatter(object):
         group_actions = set()
         inserts = {}
         for group in groups:
+            if not group._group_actions:
+                raise ValueError(f'empty group {group}')
+
             try:
                 start = actions.index(group._group_actions[0])
             except ValueError:
index d79ac5a4651d97c3553d4a28c2206950e6a05ea4..043a9cf93f771fc8b03961cbed02973fbb98e75c 100644 (file)
@@ -2582,6 +2582,13 @@ class TestMutuallyExclusiveGroupErrors(TestCase):
               '''
         self.assertEqual(parser.format_help(), textwrap.dedent(expected))
 
+    def test_empty_group(self):
+        # See issue 26952
+        parser = argparse.ArgumentParser()
+        group = parser.add_mutually_exclusive_group()
+        with self.assertRaises(ValueError):
+            parser.parse_args(['-h'])
+
 class MEMixin(object):
 
     def test_failures_when_not_required(self):
diff --git a/Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst b/Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst
new file mode 100644 (file)
index 0000000..379dbb5
--- /dev/null
@@ -0,0 +1 @@
+:mod:`argparse` raises :exc:`ValueError` with clear message when trying to render usage for an empty mutually-exclusive group. Previously it raised a cryptic :exc:`IndexError`.
\ No newline at end of file