GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [3.13] gh-86357: argparse: use str() consistently and explicitly to p… · python/cpython@d3d306a

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Lib
    • argparse.py
    • test
      • test_argparse.py
  • Misc/NEWS.d/next/Library
    • 2024-04-19-05-58-50.gh-issue-117766.J3xepp.rst
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Lib/argparse.py‎

Copy file name to clipboardExpand all lines: Lib/argparse.py
+5-7Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,7 @@ def _metavar_formatter(self, action, default_metavar):
547547
if action.metavar is not None:
548548
result = action.metavar
549549
elif action.choices is not None:
550-
choice_strs = [str(choice) for choice in action.choices]
551-
result = '{%s}' % ','.join(choice_strs)
550+
result = '{%s}' % ','.join(map(str, action.choices))
552551
else:
553552
result = default_metavar
554553

@@ -596,8 +595,7 @@ def _expand_help(self, action):
596595
if hasattr(params[name], '__name__'):
597596
params[name] = params[name].__name__
598597
if params.get('choices') is not None:
599-
choices_str = ', '.join([str(c) for c in params['choices']])
600-
params['choices'] = choices_str
598+
params['choices'] = ', '.join(map(str, params['choices']))
601599
return self._get_help_string(action) % params
602600

603601
def _iter_indented_subactions(self, action):
@@ -714,7 +712,7 @@ def _get_action_name(argument):
714712
elif argument.dest not in (None, SUPPRESS):
715713
return argument.dest
716714
elif argument.choices:
717-
return '{' + ','.join(argument.choices) + '}'
715+
return '{%s}' % ','.join(map(str, argument.choices))
718716
else:
719717
return None
720718

@@ -2595,8 +2593,8 @@ def _check_value(self, action, value):
25952593
if isinstance(choices, str):
25962594
choices = iter(choices)
25972595
if value not in choices:
2598-
args = {'value': value,
2599-
'choices': ', '.join(map(repr, action.choices))}
2596+
args = {'value': str(value),
2597+
'choices': ', '.join(map(str, action.choices))}
26002598
msg = _('invalid choice: %(value)r (choose from %(choices)s)')
26012599
raise ArgumentError(action, msg % args)
26022600

Collapse file

‎Lib/test/test_argparse.py‎

Copy file name to clipboardExpand all lines: Lib/test/test_argparse.py
+30-1Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import argparse
1616
import warnings
1717

18+
from enum import StrEnum
1819
from test.support import os_helper, captured_stderr
1920
from unittest import mock
2021

@@ -1021,6 +1022,34 @@ class TestDisallowLongAbbreviationAllowsShortGroupingPrefix(ParserTestCase):
10211022
]
10221023

10231024

1025+
class TestStrEnumChoices(TestCase):
1026+
class Color(StrEnum):
1027+
RED = "red"
1028+
GREEN = "green"
1029+
BLUE = "blue"
1030+
1031+
def test_parse_enum_value(self):
1032+
parser = argparse.ArgumentParser()
1033+
parser.add_argument('--color', choices=self.Color)
1034+
args = parser.parse_args(['--color', 'red'])
1035+
self.assertEqual(args.color, self.Color.RED)
1036+
1037+
def test_help_message_contains_enum_choices(self):
1038+
parser = argparse.ArgumentParser()
1039+
parser.add_argument('--color', choices=self.Color, help='Choose a color')
1040+
self.assertIn('[--color {red,green,blue}]', parser.format_usage())
1041+
self.assertIn(' --color {red,green,blue}', parser.format_help())
1042+
1043+
def test_invalid_enum_value_raises_error(self):
1044+
parser = argparse.ArgumentParser(exit_on_error=False)
1045+
parser.add_argument('--color', choices=self.Color)
1046+
self.assertRaisesRegex(
1047+
argparse.ArgumentError,
1048+
r"invalid choice: 'yellow' \(choose from red, green, blue\)",
1049+
parser.parse_args,
1050+
['--color', 'yellow'],
1051+
)
1052+
10241053
# ================
10251054
# Positional tests
10261055
# ================
@@ -2486,7 +2515,7 @@ def test_wrong_argument_subparsers_no_destination_error(self):
24862515
parser.parse_args(('baz',))
24872516
self.assertRegex(
24882517
excinfo.exception.stderr,
2489-
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from 'foo', 'bar'\)\n$"
2518+
r"error: argument {foo,bar}: invalid choice: 'baz' \(choose from foo, bar\)\n$"
24902519
)
24912520

24922521
def test_optional_subparsers(self):
Collapse file

‎Misc/NEWS.d/next/Library/2024-04-19-05-58-50.gh-issue-117766.J3xepp.rst‎

Copy file name to clipboard
+1Lines changed: 1 addition & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Always use :func:`str` to print ``choices`` in :mod:`argparse`.

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.