diff --git a/Lib/argparse.py b/Lib/argparse.py index 29e6ebb9634261..63a72eeaef17a7 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -758,7 +758,7 @@ def colorize(match): return spec % params return self._apply_text_markup( - _re.sub(fmt_spec, colorize, help_string, flags=_re.VERBOSE) + _re.sub(fmt_spec, colorize, str(help_string), flags=_re.VERBOSE) ) def _iter_indented_subactions(self, action): diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 1dc3f538f4ad8b..051cba821e38ca 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -7837,6 +7837,38 @@ def test_backtick_markup_in_argument_help_color_disabled(self): self.assertIn("set the `foo` value", help_text) self.assertNotIn("\x1b[", help_text) + def test_argument_help_interpolation_accepts_string_like_proxy(self): + class LazyStr: + def __init__(self, message): + self._message = message + + def __str__(self): + return self._message + + def __contains__(self, item): + return item in self._message + + def __mod__(self, other): + return self._message % other + + def strip(self): + return self._message.strip() + + parser = argparse.ArgumentParser(prog="PROG", color=True) + parser.add_argument( + "--foo", + default="bar", + help=LazyStr("set `foo` (default: %(default)s)"), + ) + + prog_extra = self.theme.prog_extra + interp = self.theme.interpolated_value + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f"set {prog_extra}foo{reset}", help_text) + self.assertIn(f"default: {interp}bar{reset}", help_text) + def test_help_with_format_specifiers(self): # GH-142950: format specifiers like %x should work with color=True parser = argparse.ArgumentParser(prog='PROG', color=True) diff --git a/Misc/NEWS.d/next/Library/2026-05-22-17-53-01.gh-issue-148468.o5fZ3K.rst b/Misc/NEWS.d/next/Library/2026-05-22-17-53-01.gh-issue-148468.o5fZ3K.rst new file mode 100644 index 00000000000000..bdd13ae243ef45 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-22-17-53-01.gh-issue-148468.o5fZ3K.rst @@ -0,0 +1,3 @@ +Fix a regression in :mod:`argparse` so colorized help formatting once again +accepts string-like proxy objects for descriptions, epilogs, and argument +help text.