Skip to content

gh-133653: Fix subclassing HelpFormatter #133668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
24 changes: 24 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix subclassing :meth:`!argparse.HelpFormatter`. Patch by Hugo van Kemenade.
Loading