Skip to content

Instantly share code, notes, and snippets.

@TakingItCasual
Created September 18, 2018 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TakingItCasual/df40932dcc30012325bfed241bdaabd0 to your computer and use it in GitHub Desktop.
Save TakingItCasual/df40932dcc30012325bfed241bdaabd0 to your computer and use it in GitHub Desktop.
argparse class to properly indent subparser help
class ProperIndentParser(argparse.ArgumentParser):
"""Use formatter_class that properly indents help in subparsers"""
def __init__(self, *args, **kwargs):
formatter_class = lambda prog: ProperIndentFormatter(prog)
argparse.ArgumentParser.__init__(
self, *args, **kwargs, formatter_class=formatter_class)
class ProperIndentFormatter(argparse.HelpFormatter):
"""Corrected _max_action_length for the indenting of subactions
Source: https://stackoverflow.com/a/32891625/2868017
"""
def add_argument(self, action):
if action.help is not argparse.SUPPRESS:
# find all invocations
get_invocation = self._format_action_invocation
invocations = [get_invocation(action)]
current_indent = self._current_indent
for subaction in self._iter_indented_subactions(action):
# compensate for the indent that will be added
indent_chg = self._current_indent - current_indent
added_indent = "x"*indent_chg
invocations.append(added_indent + get_invocation(subaction))
# update the maximum item length
invocation_length = max([len(s) for s in invocations])
action_length = invocation_length + self._current_indent
self._action_max_length = max(
self._action_max_length, action_length)
# add the item to the list
self._add_item(self._format_action, [action])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment