Skip to content

Commit 2a062f2

Browse files
gh-101979: argparse: fix a bug where parentheses in metavar argument of add_argument() were dropped (GH-102318)
(cherry picked from commit 9a478be) Co-authored-by: Yeojin Kim <[email protected]>
1 parent d4a04e5 commit 2a062f2

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
@@ -400,10 +400,18 @@ def _format_actions_usage(self, actions, groups):
400400
except ValueError:
401401
continue
402402
else:
403-
end = start + len(group._group_actions)
403+
group_action_count = len(group._group_actions)
404+
end = start + group_action_count
404405
if actions[start:end] == group._group_actions:
406+
407+
suppressed_actions_count = 0
405408
for action in group._group_actions:
406409
group_actions.add(action)
410+
if action.help is SUPPRESS:
411+
suppressed_actions_count += 1
412+
413+
exposed_actions_count = group_action_count - suppressed_actions_count
414+
407415
if not group.required:
408416
if start in inserts:
409417
inserts[start] += ' ['
@@ -413,7 +421,7 @@ def _format_actions_usage(self, actions, groups):
413421
inserts[end] += ']'
414422
else:
415423
inserts[end] = ']'
416-
else:
424+
elif exposed_actions_count > 1:
417425
if start in inserts:
418426
inserts[start] += ' ('
419427
else:
@@ -487,7 +495,6 @@ def _format_actions_usage(self, actions, groups):
487495
text = _re.sub(r'(%s) ' % open, r'\1', text)
488496
text = _re.sub(r' (%s)' % close, r'\1', text)
489497
text = _re.sub(r'%s *%s' % (open, close), r'', text)
490-
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
491498
text = text.strip()
492499

493500
# return the text

Lib/test/test_argparse.py

+22
Original file line numberDiff line numberDiff line change
@@ -3729,6 +3729,28 @@ class TestHelpUsage(HelpTestCase):
37293729
version = ''
37303730

37313731

3732+
class TestHelpUsageWithParentheses(HelpTestCase):
3733+
parser_signature = Sig(prog='PROG')
3734+
argument_signatures = [
3735+
Sig('positional', metavar='(example) positional'),
3736+
Sig('-p', '--optional', metavar='{1 (option A), 2 (option B)}'),
3737+
]
3738+
3739+
usage = '''\
3740+
usage: PROG [-h] [-p {1 (option A), 2 (option B)}] (example) positional
3741+
'''
3742+
help = usage + '''\
3743+
3744+
positional arguments:
3745+
(example) positional
3746+
3747+
options:
3748+
-h, --help show this help message and exit
3749+
-p {1 (option A), 2 (option B)}, --optional {1 (option A), 2 (option B)}
3750+
'''
3751+
version = ''
3752+
3753+
37323754
class TestHelpOnlyUserGroups(HelpTestCase):
37333755
"""Test basic usage messages"""
37343756

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)