Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-26510: Allow argparse add_subparsers to take required kwarg. #3027

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1539,8 +1539,8 @@ Sub-commands

.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
[parser_class], [action], \
[option_string], [dest], [help], \
[metavar])
[option_string], [dest], [required] \
[help], [metavar])

Many programs split up their functionality into a number of sub-commands,
for example, the ``svn`` program can invoke sub-commands like ``svn
Expand Down Expand Up @@ -1576,6 +1576,9 @@ Sub-commands
* dest_ - name of the attribute under which sub-command name will be
stored; by default ``None`` and no value is stored

* required_ - Whether or not a subcommand must be provided, by default
``True``.

* help_ - help for sub-parser group in help output, by default ``None``

* metavar_ - string presenting available sub-commands in help; by default it
Expand Down
2 changes: 2 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,7 @@ def __init__(self,
prog,
parser_class,
dest=SUPPRESS,
required=True,
help=None,
metavar=None):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For maximum backward compatibility, the new parameter should be added to the end.

(I don’t personnally write calls like something('abc', SUPPRESS, True, None, None) but they are supported, and should not be broken when possible.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add_subparsers itself takes no keyword arguments so I don't think there's a concern of the private api here.

>>> parser.add_subparsers('foo', True, False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add_subparsers() takes 1 positional argument but 4 were given

(the 1 positional argument here being self)

The ordering I chose was intentional to match the signatures in the rest of the file.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@merwok do I monty-python it up now? I'm unclear on the process for dismissing a review :P

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The review holding this up is «please update docs and news» :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoops totally missed that! I'll get right on it :)


Expand All @@ -1079,6 +1080,7 @@ def __init__(self,
dest=dest,
nargs=PARSER,
choices=self._name_parser_map,
required=required,
help=help,
metavar=metavar)

Expand Down
37 changes: 36 additions & 1 deletion Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1807,7 +1807,7 @@ def _get_parser(self, subparser_help=False, prefix_chars=None,
'bar', type=float, help='bar help')

# check that only one subparsers argument can be added
subparsers_kwargs = {}
subparsers_kwargs = {'required': False}
if aliases:
subparsers_kwargs['metavar'] = 'COMMAND'
subparsers_kwargs['title'] = 'commands'
Expand Down Expand Up @@ -1907,6 +1907,41 @@ def test_dest(self):
self.assertEqual(NS(foo=False, bar='1', baz='2'),
parser.parse_args('1 2'.split()))

def _test_required_subparsers(self, parser):
# Should parse the sub command
ret = parser.parse_args(['run'])
self.assertEqual(ret.command, 'run')

# Error when the command is missing
self.assertArgumentParserError(parser.parse_args, ())

def test_required_subparsers_via_attribute(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(dest='command')
subparsers.required = True
subparsers.add_parser('run')
self._test_required_subparsers(parser)

def test_required_subparsers_via_kwarg(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(dest='command', required=True)
subparsers.add_parser('run')
self._test_required_subparsers(parser)

def test_required_subparsers_default(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(dest='command')
subparsers.add_parser('run')
self._test_required_subparsers(parser)

def test_optional_subparsers(self):
parser = ErrorRaisingArgumentParser()
subparsers = parser.add_subparsers(dest='command', required=False)
subparsers.add_parser('run')
# No error here
ret = parser.parse_args(())
self.assertIsNone(ret.command)

def test_help(self):
self.assertEqual(self.parser.format_usage(),
'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
argparse subparsers are now required by default. This matches behaviour in Python 2.
For optional subparsers, use the new parameter ``add_subparsers(required=False)``.
Patch by Anthony Sottile.