diff --git a/Lib/argparse.py b/Lib/argparse.py index f13ac82dbc50b3..06d8e6cc1f1ca2 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -2723,9 +2723,17 @@ def format_help(self): return formatter.format_help() def _get_formatter(self): - if isinstance(self.formatter_class, type) and issubclass( - self.formatter_class, HelpFormatter - ): + import inspect + if len( + [v.kind for (k, v) in + inspect.signature(self.formatter_class).parameters.items() + if k in ('prefix_chars', 'color') + and v.kind in ( + inspect._ParameterKind.POSITIONAL_OR_KEYWORD, + inspect._ParameterKind.KEYWORD_ONLY, + ) + ] + ) == 2: return self.formatter_class( prog=self.prog, prefix_chars=self.prefix_chars, diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 5a6be1180c1a3e..d9bb58c1c8f322 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -5176,6 +5176,30 @@ class TestHelpTupleMetavarPositional(HelpTestCase): version = '' +class TestHelpFormatter(HelpTestCase): + """Test the HelpFormatter""" + + # Test subclassing the help formatter + class MyFormatter(argparse.HelpFormatter): + def __init__(self, prog) -> None: + super().__init__(prog) + + parser_signature = Sig( + prog="PROG", + formatter_class=MyFormatter, + description="Test with subclassing the help formatter", + ) + usage = '''\ + usage: PROG [-h] + ''' + help = usage + '''\ + + Test with subclassing the help formatter + + options: + -h, --help show this help message and exit + ''' + class TestHelpRawText(HelpTestCase): """Test the RawTextHelpFormatter""" diff --git a/Misc/NEWS.d/next/Library/2025-05-08-16-28-05.gh-issue-133653.7cxHXN.rst b/Misc/NEWS.d/next/Library/2025-05-08-16-28-05.gh-issue-133653.7cxHXN.rst new file mode 100644 index 00000000000000..d49de56cee719d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-05-08-16-28-05.gh-issue-133653.7cxHXN.rst @@ -0,0 +1 @@ +Fix subclassing :meth:`!argparse.HelpFormatter`. Patch by Hugo van Kemenade.