Skip to content

Commit d21b0b5

Browse files
authored
gh-113008: Correct argparse usage output for required, mutually exclusive groups (GH-113085)
1 parent 4a5e4aa commit d21b0b5

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

Lib/argparse.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,12 +395,12 @@ def _get_actions_usage_parts(self, actions, groups):
395395
continue
396396

397397
try:
398-
start = actions.index(group._group_actions[0])
398+
start = min(actions.index(item) for item in group._group_actions)
399399
except ValueError:
400400
continue
401401
else:
402402
end = start + len(group._group_actions)
403-
if actions[start:end] == group._group_actions:
403+
if set(actions[start:end]) == set(group._group_actions):
404404
group_actions.update(group._group_actions)
405405
inserts[start, end] = group
406406

Lib/test/test_argparse.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2902,6 +2902,29 @@ def test_help(self):
29022902
'''
29032903
self.assertEqual(parser.format_help(), textwrap.dedent(expected))
29042904

2905+
def test_optional_order(self):
2906+
parser = ErrorRaisingArgumentParser(prog='PROG')
2907+
group = parser.add_mutually_exclusive_group(required=True)
2908+
group.add_argument('--foo')
2909+
group.add_argument('bar', nargs='?')
2910+
expected = '''\
2911+
usage: PROG [-h] (--foo FOO | bar)
2912+
2913+
positional arguments:
2914+
bar
2915+
2916+
options:
2917+
-h, --help show this help message and exit
2918+
--foo FOO
2919+
'''
2920+
self.assertEqual(parser.format_help(), textwrap.dedent(expected))
2921+
2922+
parser = ErrorRaisingArgumentParser(prog='PROG')
2923+
group = parser.add_mutually_exclusive_group(required=True)
2924+
group.add_argument('bar', nargs='?')
2925+
group.add_argument('--foo')
2926+
self.assertEqual(parser.format_help(), textwrap.dedent(expected))
2927+
29052928
def test_help_subparser_all_mutually_exclusive_group_members_suppressed(self):
29062929
self.maxDiff = None
29072930
parser = ErrorRaisingArgumentParser(prog='PROG')
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Correct argparse usage output for required, mutually exclusive groups containing a positional argument

0 commit comments

Comments
 (0)