Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active February 28, 2024 22:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panzi/b4a51b3968f67b9ff4c99459fb9c5b3d to your computer and use it in GitHub Desktop.
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)`
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)))
@chris-vecchio
Copy link

Thanks for sharing this! You just saved me a ton of time!

@swirle13
Copy link

swirle13 commented Feb 9, 2024

Thank you so much for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment