diff --git a/Lib/argparse.py b/Lib/argparse.py --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -555,8 +555,8 @@ 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 = action._choices_str(',', str, format='{%s}', + default=default_metavar) else: result = default_metavar @@ -594,8 +594,11 @@ for name in list(params): 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']]) + if action.choices is not None: + metavar = action.metavar + if metavar is None: + metavar = self._get_default_metavar(action) + choices_str = action._choices_str(', ', str, default=metavar) params['choices'] = choices_str return self._get_help_string(action) % params @@ -621,6 +624,11 @@ def _get_help_string(self, action): return action.help + def _get_default_metavar(self, action): + if action.option_strings: + return self._get_default_metavar_for_optional(action) + return self._get_default_metavar_for_positional(action) + def _get_default_metavar_for_optional(self, action): return action.dest.upper() @@ -816,6 +824,14 @@ ] return [(name, getattr(self, name)) for name in names] + def _choices_str(self, sep, to_str, format='%s', default=''): + try: + choices = iter(self.choices) + except TypeError: + return default + choices_str = sep.join([to_str(choice) for choice in choices]) + return format % choices_str + def __call__(self, parser, namespace, values, option_string=None): raise NotImplementedError(_('.__call__() not defined')) @@ -2294,9 +2310,9 @@ def _check_value(self, action, value): # converted value must be one of the choices (if specified) if action.choices is not None and value not in action.choices: - args = {'value': value, - 'choices': ', '.join(map(repr, action.choices))} - msg = _('invalid choice: %(value)r (choose from %(choices)s)') + end = action._choices_str(', ', repr, format=' (choose from %s)') + args = {'value': value, 'ending': end} + msg = _('invalid choice: %(value)r%(ending)s') raise ArgumentError(action, msg % args) # =======================