Skip to content

Commit

Permalink
pythongh-101979: argparse: fix a bug where parentheses in metavar arg…
Browse files Browse the repository at this point in the history
…ument of add_argument() were dropped (pythonGH-102318)

(cherry picked from commit 9a478be)

Co-authored-by: Yeojin Kim <[email protected]>
  • Loading branch information
yeojin-dev authored and miss-islington committed Mar 5, 2023
1 parent d4a04e5 commit 20dfd9a
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
13 changes: 10 additions & 3 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,18 @@ def _format_actions_usage(self, actions, groups):
except ValueError:
continue
else:
end = start + len(group._group_actions)
group_action_count = len(group._group_actions)
end = start + group_action_count
if actions[start:end] == group._group_actions:

suppressed_actions_count = 0
for action in group._group_actions:
group_actions.add(action)
if action.help is SUPPRESS:
suppressed_actions_count += 1

exposed_actions_count = group_action_count - suppressed_actions_count

if not group.required:
if start in inserts:
inserts[start] += ' ['
Expand All @@ -413,7 +421,7 @@ def _format_actions_usage(self, actions, groups):
inserts[end] += ']'
else:
inserts[end] = ']'
else:
elif exposed_actions_count > 1:
if start in inserts:
inserts[start] += ' ('
else:
Expand Down Expand Up @@ -487,7 +495,6 @@ def _format_actions_usage(self, actions, groups):
text = _re.sub(r'(%s) ' % open, r'\1', text)
text = _re.sub(r' (%s)' % close, r'\1', text)
text = _re.sub(r'%s *%s' % (open, close), r'', text)
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
text = text.strip()

# return the text
Expand Down
22 changes: 22 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3729,6 +3729,28 @@ class TestHelpUsage(HelpTestCase):
version = ''


class TestHelpUsageWithParentheses(HelpTestCase):
parser_signature = Sig(prog='PROG')
argument_signatures = [
Sig('positional', metavar='(example) positional'),
Sig('-p', '--optional', metavar='{1 (option A), 2 (option B)}'),
]

usage = '''\
usage: PROG [-h] [-p {1 (option A), 2 (option B)}] (example) positional
'''
help = usage + '''\
positional arguments:
(example) positional
options:
-h, --help show this help message and exit
-p {1 (option A), 2 (option B)}, --optional {1 (option A), 2 (option B)}
'''
version = ''


class TestHelpOnlyUserGroups(HelpTestCase):
"""Test basic usage messages"""

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

0 comments on commit 20dfd9a

Please sign in to comment.