Last active
February 28, 2024 22:32
-
-
Save panzi/b4a51b3968f67b9ff4c99459fb9c5b3d to your computer and use it in GitHub Desktop.
Python argparse help formatter that keeps new lines and doesn't break words (so URLs are preserved), but still wraps lines. Use with: `argparse.ArgumentParser(formatter_class=SmartFormatter)`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from typing import List | |
class SmartFormatter(argparse.HelpFormatter): | |
def _split_lines(self, text: str, width: int) -> List[str]: | |
lines: List[str] = [] | |
for line_str in text.split('\n'): | |
line: List[str] = [] | |
line_len = 0 | |
for word in line_str.split(): | |
word_len = len(word) | |
next_len = line_len + word_len | |
if line: next_len += 1 | |
if next_len > width: | |
lines.append(' '.join(line)) | |
line.clear() | |
line_len = 0 | |
elif line: | |
line_len += 1 | |
line.append(word) | |
line_len += word_len | |
lines.append(' '.join(line)) | |
return lines | |
def _fill_text(self, text: str, width: int, indent: str) -> str: | |
return '\n'.join(indent + line for line in self._split_lines(text, width - len(indent))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this! You just saved me a ton of time!