Skip to content

Commit e95217a

Browse files
committed
bpo-14074: argparse doesn't allow metavar to be a tuple
Currently argparse allows nargs>1 for positional arguments but doesn't allow metavar to be a tuple: import argparse parser = argparse.ArgumentParser() parser.add_argument('foo', nargs=2, metavar=('bar', 'baz')) args = parser.parse_args() The above code will raise exception both with and without '--help'. This patch fixed some functions about metavar processing so the above code will pass.
1 parent a09bc3a commit e95217a

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

Lib/argparse.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,8 @@ def _format_action(self, action):
553553
def _format_action_invocation(self, action):
554554
if not action.option_strings:
555555
default = self._get_default_metavar_for_positional(action)
556+
if isinstance(action.nargs, int):
557+
return ' '.join(self._metavar_formatter(action, default)(1))
556558
metavar, = self._metavar_formatter(action, default)(1)
557559
return metavar
558560

@@ -730,6 +732,9 @@ def _get_action_name(argument):
730732
elif argument.option_strings:
731733
return '/'.join(argument.option_strings)
732734
elif argument.metavar not in (None, SUPPRESS):
735+
if isinstance(
736+
argument.nargs, int) and isinstance(argument.metavar, tuple):
737+
return ' '.join(argument.metavar)
733738
return argument.metavar
734739
elif argument.dest not in (None, SUPPRESS):
735740
return argument.dest

Lib/test/test_argparse.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4226,6 +4226,28 @@ class TestHelpTupleMetavar(HelpTestCase):
42264226
version = ''
42274227

42284228

4229+
class TestHelpTupleMetavarPositional(HelpTestCase):
4230+
"""Test specifying metavar on a Positional as a tuple"""
4231+
4232+
parser_signature = Sig(prog='PROG')
4233+
argument_signatures = [
4234+
Sig('foo', help='foo help', nargs=2, metavar=('bar', 'baz'))
4235+
]
4236+
argument_group_signatures = []
4237+
usage = '''\
4238+
usage: PROG [-h] bar baz
4239+
'''
4240+
help = usage + '''\
4241+
4242+
positional arguments:
4243+
bar baz foo help
4244+
4245+
options:
4246+
-h, --help show this help message and exit
4247+
'''
4248+
version = ''
4249+
4250+
42294251
class TestHelpRawText(HelpTestCase):
42304252
"""Test the RawTextHelpFormatter"""
42314253

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`argparse` metavar processing to allow positional arguments to have a
2+
tuple metavar.

0 commit comments

Comments
 (0)