From 8e4c96295bd78ae5f70b908e5dbac0da7c4c21bd Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Wed, 15 Dec 2021 04:20:04 -0800 Subject: =?UTF-8?q?bpo-26952:=20[argparse]=20clearer=20error=20when=20form?= =?UTF-8?q?atting=20an=20empty=20mutually=E2=80=A6=20(GH-30099)=20(GH-3011?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (cherry picked from commit 86de99588db3beff964137f4fe27dd1077a09b35) Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com> --- Lib/argparse.py | 3 +++ Lib/test/test_argparse.py | 7 +++++++ Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst | 1 + 3 files changed, 11 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst diff --git a/Lib/argparse.py b/Lib/argparse.py index 9eed24c..b2db312 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -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: diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index ec49b2a..c96a540 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -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 index 0000000..379dbb5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-12-14-13-18-45.bpo-26952.hjhISq.rst @@ -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 -- cgit v0.12