Skip to content

Commit 9a478be

Browse files
authored
gh-101979: argparse: fix a bug where parentheses in metavar argument of add_argument() were dropped (#102318)
1 parent 66aa78c commit 9a478be

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

Lib/argparse.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -403,10 +403,18 @@ def _format_actions_usage(self, actions, groups):
403403
except ValueError:
404404
continue
405405
else:
406-
end = start + len(group._group_actions)
406+
group_action_count = len(group._group_actions)
407+
end = start + group_action_count
407408
if actions[start:end] == group._group_actions:
409+
410+
suppressed_actions_count = 0
408411
for action in group._group_actions:
409412
group_actions.add(action)
413+
if action.help is SUPPRESS:
414+
suppressed_actions_count += 1
415+
416+
exposed_actions_count = group_action_count - suppressed_actions_count
417+
410418
if not group.required:
411419
if start in inserts:
412420
inserts[start] += ' ['
@@ -416,7 +424,7 @@ def _format_actions_usage(self, actions, groups):
416424
inserts[end] += ']'
417425
else:
418426
inserts[end] = ']'
419-
else:
427+
elif exposed_actions_count > 1:
420428
if start in inserts:
421429
inserts[start] += ' ('
422430
else:
@@ -490,7 +498,6 @@ def _format_actions_usage(self, actions, groups):
490498
text = _re.sub(r'(%s) ' % open, r'\1', text)
491499
text = _re.sub(r' (%s)' % close, r'\1', text)
492500
text = _re.sub(r'%s *%s' % (open, close), r'', text)
493-
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
494501
text = text.strip()
495502

496503
# return the text

Lib/test/test_argparse.py

+22
Original file line numberDiff line numberDiff line change
@@ -3764,6 +3764,28 @@ class TestHelpUsage(HelpTestCase):
37643764
version = ''
37653765

37663766

3767+
class TestHelpUsageWithParentheses(HelpTestCase):
3768+
parser_signature = Sig(prog='PROG')
3769+
argument_signatures = [
3770+
Sig('positional', metavar='(example) positional'),
3771+
Sig('-p', '--optional', metavar='{1 (option A), 2 (option B)}'),
3772+
]
3773+
3774+
usage = '''\
3775+
usage: PROG [-h] [-p {1 (option A), 2 (option B)}] (example) positional
3776+
'''
3777+
help = usage + '''\
3778+
3779+
positional arguments:
3780+
(example) positional
3781+
3782+
options:
3783+
-h, --help show this help message and exit
3784+
-p {1 (option A), 2 (option B)}, --optional {1 (option A), 2 (option B)}
3785+
'''
3786+
version = ''
3787+
3788+
37673789
class TestHelpOnlyUserGroups(HelpTestCase):
37683790
"""Test basic usage messages"""
37693791

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug where parentheses in the ``metavar`` argument to :meth:`argparse.ArgumentParser.add_argument` were
2+
dropped. Patch by Yeojin Kim.

0 commit comments

Comments
 (0)