]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-86357: argparse: use str() consistently and explicitly to print choices...
authorSerhiy Storchaka <storchaka@gmail.com>
Mon, 14 Oct 2024 07:09:06 +0000 (10:09 +0300)
committerGitHub <noreply@github.com>
Mon, 14 Oct 2024 07:09:06 +0000 (07:09 +0000)
(cherry picked from commit 66b3922b97388c328c9bd8df050eef11c0261fae)

Signed-off-by: Jan Chren ~rindeal <dev.rindeal@gmail.com>
Co-authored-by: rindeal <dev.rindeal@gmail.com>
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2024-04-19-05-58-50.gh-issue-117766.J3xepp.rst [new file with mode: 0644]

index 663e40c8e2d7a64639311a8a5c0fa003e61fc8f8..395bb1cd13b96679dc09dcd49ba3d2f0295f7e66 100644 (file)
@@ -547,8 +547,7 @@ class HelpFormatter(object):
         if action.metavar is not None:
             result = action.metavar
         elif action.choices is not None:
-            choice_strs = [str(choice) for choice in action.choices]
-            result = '{%s}' % ','.join(choice_strs)
+            result = '{%s}' % ','.join(map(str, action.choices))
         else:
             result = default_metavar
 
@@ -596,8 +595,7 @@ class HelpFormatter(object):
             if hasattr(params[name], '__name__'):
                 params[name] = params[name].__name__
         if params.get('choices') is not None:
-            choices_str = ', '.join([str(c) for c in params['choices']])
-            params['choices'] = choices_str
+            params['choices'] = ', '.join(map(str, params['choices']))
         return self._get_help_string(action) % params
 
     def _iter_indented_subactions(self, action):
@@ -714,7 +712,7 @@ def _get_action_name(argument):
     elif argument.dest not in (None, SUPPRESS):
         return argument.dest
     elif argument.choices:
-        return '{' + ','.join(argument.choices) + '}'
+        return '{%s}' % ','.join(map(str, argument.choices))
     else:
         return None
 
@@ -2595,8 +2593,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
             if isinstance(choices, str):
                 choices = iter(choices)
             if value not in choices:
-                args = {'value': value,
-                        'choices': ', '.join(map(repr, action.choices))}
+                args = {'value': str(value),
+                        'choices': ', '.join(map(str, action.choices))}
                 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
                 raise ArgumentError(action, msg % args)
 
index 373c04b61a2615199fa7e3b6b89e00b3dd3ed97e..77af8642c077a0690b4b17e070fa8e090b3da0c4 100644 (file)
@@ -15,6 +15,7 @@ import unittest
 import argparse
 import warnings
 
+from enum import StrEnum
 from test.support import os_helper, captured_stderr
 from unittest import mock
 
@@ -1021,6 +1022,34 @@ class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
     ]
 
 
+class TestStrEnumChoices(TestCase):
+    class Color(StrEnum):
+        RED = "red"
+        GREEN = "green"
+        BLUE = "blue"
+
+    def test_parse_enum_value(self):
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--color', choices=self.Color)
+        args = parser.parse_args(['--color', 'red'])
+        self.assertEqual(args.color, self.Color.RED)
+
+    def test_help_message_contains_enum_choices(self):
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--color', choices=self.Color, help='Choose a color')
+        self.assertIn('[--color {red,green,blue}]', parser.format_usage())
+        self.assertIn('  --color {red,green,blue}', parser.format_help())
+
+    def test_invalid_enum_value_raises_error(self):
+        parser = argparse.ArgumentParser(exit_on_error=False)
+        parser.add_argument('--color', choices=self.Color)
+        self.assertRaisesRegex(
+            argparse.ArgumentError,
+            r"invalid choice: 'yellow' \(choose from red, green, blue\)",
+            parser.parse_args,
+            ['--color', 'yellow'],
+        )
+
 # ================
 # Positional tests
 # ================
@@ -2486,7 +2515,7 @@ class TestAddSubparsers(TestCase):
             parser.parse_args(('baz',))
         self.assertRegex(
             excinfo.exception.stderr,
-            r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
+            r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from foo, bar\)\n$"
         )
 
     def test_optional_subparsers(self):
diff --git a/Misc/NEWS.d/next/Library/2024-04-19-05-58-50.gh-issue-117766.J3xepp.rst b/Misc/NEWS.d/next/Library/2024-04-19-05-58-50.gh-issue-117766.J3xepp.rst
new file mode 100644 (file)
index 0000000..d090f93
--- /dev/null
@@ -0,0 +1 @@
+Always use :func:`str` to print ``choices`` in :mod:`argparse`.