diff --git a/Lib/argparse.py b/Lib/argparse.py index b44fa4f0f65..8a81801ba92 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 f3edde3de8e..eb37d4d365d 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -2601,6 +2601,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 00000000000..379dbb55c7c --- /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