Skip to content

Commit c22cbf8

Browse files
miss-islingtonsavannahostrowskiblurb-it[bot]hugovk
authored
[3.15] GH-148468: Accept string-like proxy objects in colorized argparse help (GH-154653) (#154946)
GH-148468: Accept string-like proxy objects in colorized argparse help (GH-154653) (cherry picked from commit a147366) Co-authored-by: Savannah Ostrowski <savannah@python.org> 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 f82903b commit c22cbf8

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
@@ -711,7 +711,7 @@ def _format_args(self, action, default_metavar):
711711
return result
712712

713713
def _expand_help(self, action):
714-
help_string = self._get_help_string(action)
714+
help_string = str(self._get_help_string(action))
715715
if '%' not in help_string:
716716
return self._apply_text_markup(help_string)
717717
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
@@ -7893,6 +7893,41 @@ def test_backtick_markup_in_argument_help_color_disabled(self):
78937893
self.assertIn("set the `foo` value", help_text)
78947894
self.assertNotIn("\x1b[", help_text)
78957895

7896+
def test_argument_help_interpolation_accepts_string_like_proxy(self):
7897+
class LazyStr:
7898+
def __init__(self, message):
7899+
self._message = message
7900+
7901+
def __str__(self):
7902+
return self._message
7903+
7904+
def __getattr__(self, name):
7905+
return getattr(str(self), name)
7906+
7907+
def __contains__(self, item):
7908+
return item in self._message
7909+
7910+
def __mod__(self, other):
7911+
return self._message % other
7912+
7913+
parser = argparse.ArgumentParser(prog="PROG", color=True)
7914+
parser.add_argument(
7915+
"--foo",
7916+
default="bar",
7917+
help=LazyStr("foo (default: %(default)s)"),
7918+
)
7919+
parser.add_argument(
7920+
"--baz",
7921+
help=LazyStr("baz plain text"),
7922+
)
7923+
7924+
interp = self.theme.interpolated_value
7925+
reset = self.theme.reset
7926+
7927+
help_text = parser.format_help()
7928+
self.assertIn(f"foo (default: {interp}bar{reset})", help_text)
7929+
self.assertIn("baz plain text", help_text)
7930+
78967931
def test_help_with_format_specifiers(self):
78977932
# GH-142950: format specifiers like %x should work with color=True
78987933
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)