]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-39716: Raise on conflicting subparser names. (GH-18605)
authorAntony Lee <anntzer.lee@gmail.com>
Sun, 1 May 2022 06:04:50 +0000 (08:04 +0200)
committerGitHub <noreply@github.com>
Sun, 1 May 2022 06:04:50 +0000 (23:04 -0700)
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
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2020-02-22-12-02-11.bpo-39716.z2WhDQ.rst [new file with mode: 0644]

index 668e1d416231fce19a6a2b68b60ac0f556755cec..c47aeffc2c3f6ca7bf2e32cf1184f9d701c7888e 100644 (file)
@@ -1171,6 +1171,13 @@ class _SubParsersAction(Action):
 
         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')
index 5777cb50f7e5392979bf9e6aba1e5c2af3c5fb9a..794b9df3796df451dbf7748dc7e3cdc72ecff807 100644 (file)
@@ -4804,6 +4804,19 @@ class TestConflictHandling(TestCase):
               --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
diff --git a/Misc/NEWS.d/next/Library/2020-02-22-12-02-11.bpo-39716.z2WhDQ.rst b/Misc/NEWS.d/next/Library/2020-02-22-12-02-11.bpo-39716.z2WhDQ.rst
new file mode 100644 (file)
index 0000000..f122811
--- /dev/null
@@ -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.