Skip to content

Commit

Permalink
bpo-39716: Raise on conflicting subparser names. (pythonGH-18605)
Browse files Browse the repository at this point in the history
Raise an ArgumentError when the same subparser name is added twice to an
ArgumentParser.  This is consistent with the (default) behavior when the
same option string is added twice to an ArgumentParser.

(Support for `conflict_handler="resolve"` could be considered as a
followup feature, although real use cases seem even rarer than
"resolve"ing option-strings.)

Automerge-Triggered-By: GH:rhettinger
  • Loading branch information
anntzer authored May 1, 2022
1 parent 9588f88 commit ad5e852
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,13 @@ def add_parser(self, name, **kwargs):

aliases = kwargs.pop('aliases', ())

if name in self._name_parser_map:
raise ArgumentError(self, _('conflicting subparser: %s') % name)
for alias in aliases:
if alias in self._name_parser_map:
raise ArgumentError(
self, _('conflicting subparser alias: %s') % alias)

# create a pseudo-action to hold the choice help
if 'help' in kwargs:
help = kwargs.pop('help')
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -4804,6 +4804,19 @@ def test_resolve_error(self):
--spam NEW_SPAM
'''))

def test_subparser_conflict(self):
parser = argparse.ArgumentParser()
sp = parser.add_subparsers()
sp.add_parser('fullname', aliases=['alias'])
self.assertRaises(argparse.ArgumentError,
sp.add_parser, 'fullname')
self.assertRaises(argparse.ArgumentError,
sp.add_parser, 'alias')
self.assertRaises(argparse.ArgumentError,
sp.add_parser, 'other', aliases=['fullname'])
self.assertRaises(argparse.ArgumentError,
sp.add_parser, 'other', aliases=['alias'])


# =============================
# Help and Version option tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Raise an ArgumentError when the same subparser name is added twice to an
`argparse.ArgumentParser`. This is consistent with the (default) behavior
when the same option string is added twice to an ArgumentParser.

0 comments on commit ad5e852

Please sign in to comment.