Skip to content

Commit ad5e852

Browse files
authored
bpo-39716: Raise on conflicting subparser names. (GH-18605)
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
1 parent 9588f88 commit ad5e852

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

Lib/argparse.py

+7
Original file line numberDiff line numberDiff line change
@@ -1171,6 +1171,13 @@ def add_parser(self, name, **kwargs):
11711171

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

1174+
if name in self._name_parser_map:
1175+
raise ArgumentError(self, _('conflicting subparser: %s') % name)
1176+
for alias in aliases:
1177+
if alias in self._name_parser_map:
1178+
raise ArgumentError(
1179+
self, _('conflicting subparser alias: %s') % alias)
1180+
11741181
# create a pseudo-action to hold the choice help
11751182
if 'help' in kwargs:
11761183
help = kwargs.pop('help')

Lib/test/test_argparse.py

+13
Original file line numberDiff line numberDiff line change
@@ -4804,6 +4804,19 @@ def test_resolve_error(self):
48044804
--spam NEW_SPAM
48054805
'''))
48064806

4807+
def test_subparser_conflict(self):
4808+
parser = argparse.ArgumentParser()
4809+
sp = parser.add_subparsers()
4810+
sp.add_parser('fullname', aliases=['alias'])
4811+
self.assertRaises(argparse.ArgumentError,
4812+
sp.add_parser, 'fullname')
4813+
self.assertRaises(argparse.ArgumentError,
4814+
sp.add_parser, 'alias')
4815+
self.assertRaises(argparse.ArgumentError,
4816+
sp.add_parser, 'other', aliases=['fullname'])
4817+
self.assertRaises(argparse.ArgumentError,
4818+
sp.add_parser, 'other', aliases=['alias'])
4819+
48074820

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

0 commit comments

Comments
 (0)