Skip to content

Commit a147366

Browse files
savannahostrowskiblurb-it[bot]hugovk
authored
GH-148468: Accept string-like proxy objects in colorized argparse help (#154653)
Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
1 parent 2f381f5 commit a147366

3 files changed

Lines changed: 37 additions & 1 deletion

File tree

Lib/argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -713,7 +713,7 @@ def _format_args(self, action, default_metavar):
713713
return result
714714

715715
def _expand_help(self, action):
716-
help_string = self._get_help_string(action)
716+
help_string = str(self._get_help_string(action))
717717
if '%' not in help_string:
718718
return self._apply_text_markup(help_string)
719719
params = dict(vars(action), prog=self._prog)

Lib/test/test_argparse.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7898,6 +7898,41 @@ def test_backtick_markup_in_argument_help_color_disabled(self):
78987898
self.assertIn("set the `foo` value", help_text)
78997899
self.assertNotIn("\x1b[", help_text)
79007900

7901+
def test_argument_help_interpolation_accepts_string_like_proxy(self):
7902+
class LazyStr:
7903+
def __init__(self, message):
7904+
self._message = message
7905+
7906+
def __str__(self):
7907+
return self._message
7908+
7909+
def __getattr__(self, name):
7910+
return getattr(str(self), name)
7911+
7912+
def __contains__(self, item):
7913+
return item in self._message
7914+
7915+
def __mod__(self, other):
7916+
return self._message % other
7917+
7918+
parser = argparse.ArgumentParser(prog="PROG", color=True)
7919+
parser.add_argument(
7920+
"--foo",
7921+
default="bar",
7922+
help=LazyStr("foo (default: %(default)s)"),
7923+
)
7924+
parser.add_argument(
7925+
"--baz",
7926+
help=LazyStr("baz plain text"),
7927+
)
7928+
7929+
interp = self.theme.interpolated_value
7930+
reset = self.theme.reset
7931+
7932+
help_text = parser.format_help()
7933+
self.assertIn(f"foo (default: {interp}bar{reset})", help_text)
7934+
self.assertIn("baz plain text", help_text)
7935+
79017936
def test_help_with_format_specifiers(self):
79027937
# GH-142950: format specifiers like %x should work with color=True
79037938
parser = argparse.ArgumentParser(prog='PROG', color=True)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a regression in :mod:`argparse` where colorized argument help containing format specifiers did not accept string-like proxy objects.

0 commit comments

Comments
 (0)