Skip to content

Commit 86de995

Browse files
authored
bpo-26952: [argparse] clearer error when formatting an empty mutually… (GH-30099)
1 parent f54fee7 commit 86de995

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

Lib/argparse.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,9 @@ def _format_actions_usage(self, actions, groups):
392392
group_actions = set()
393393
inserts = {}
394394
for group in groups:
395+
if not group._group_actions:
396+
raise ValueError(f'empty group {group}')
397+
395398
try:
396399
start = actions.index(group._group_actions[0])
397400
except ValueError:

Lib/test/test_argparse.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2601,6 +2601,13 @@ def test_help(self):
26012601
'''
26022602
self.assertEqual(parser.format_help(), textwrap.dedent(expected))
26032603

2604+
def test_empty_group(self):
2605+
# See issue 26952
2606+
parser = argparse.ArgumentParser()
2607+
group = parser.add_mutually_exclusive_group()
2608+
with self.assertRaises(ValueError):
2609+
parser.parse_args(['-h'])
2610+
26042611
class MEMixin(object):
26052612

26062613
def test_failures_when_not_required(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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`.

0 commit comments

Comments
 (0)