Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-86357: argparse: use str() consistently and explicitly to print choices#117766

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
serhiy-storchaka merged 1 commit intopython:mainfromrindeal:patch-2
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
argparse: use str() consistently and explicitly to print choices
Fixes:#86357Signed-off-by: Jan Chren ~rindeal <dev.rindeal@gmail.com>
  • Loading branch information
@rindeal
rindeal committedOct 14, 2024
commit105ff30e6c39d10f6358ca7a3a2654ec6cf7db4d
12 changes: 5 additions & 7 deletionsLib/argparse.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -547,8 +547,7 @@ def _metavar_formatter(self, action, default_metavar):
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

Expand DownExpand Up@@ -599,8 +598,7 @@ def _expand_help(self, action):
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):
Expand DownExpand Up@@ -717,7 +715,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

Expand DownExpand Up@@ -2607,8 +2605,8 @@ def _check_value(self, action, value):
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)

Expand Down
31 changes: 30 additions & 1 deletionLib/test/test_argparse.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,6 +16,7 @@
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
Expand DownExpand Up@@ -985,6 +986,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
# ================
Expand DownExpand Up@@ -2485,7 +2514,7 @@ def test_wrong_argument_subparsers_no_destination_error(self):
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):
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
Always use :func:`str` to print ``choices`` in :mod:`argparse`.

[8]ページ先頭

©2009-2025 Movatter.jp