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
elif hasattr(value, '__name__'):
params[name] = value.__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 help_string % params
def _iter_indented_subactions(self, action):
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
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)
import argparse
import warnings
+from enum import StrEnum
from test.support import captured_stderr
from test.support import import_helper
from test.support import os_helper
]
+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
# ================
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):