CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rich-argparse

Rich help formatters for argparse and optparse that enhance CLI help output with colors and formatting

Pending
Overview
Eval results
Files

argparse-formatters.mddocs/

Argparse Formatters

Core rich formatting classes that replace argparse's built-in help formatters with enhanced visual output. These formatters provide customizable colors, syntax highlighting, and rich markup support while maintaining full compatibility with existing argparse code.

Capabilities

RichHelpFormatter

The main formatter class that provides rich, colorful help output for argparse. It's the drop-in replacement for argparse.HelpFormatter with extensive customization options.

class RichHelpFormatter(argparse.HelpFormatter):
    """An argparse HelpFormatter class that renders using rich."""
    
    # Class attributes for customization
    group_name_formatter: ClassVar[Callable[[str], str]] = str.title
    """A function that formats group names. Defaults to str.title."""
    
    styles: ClassVar[dict[str, StyleType]] = {
        "argparse.args": "cyan",
        "argparse.groups": "dark_orange", 
        "argparse.help": "default",
        "argparse.metavar": "dark_cyan",
        "argparse.syntax": "bold",
        "argparse.text": "default",
        "argparse.prog": "grey50",
        "argparse.default": "italic",
    }
    """A dict of rich styles to control the formatter styles."""
    
    highlights: ClassVar[list[str]]
    """A list of regex patterns to highlight in the help text."""
    
    usage_markup: ClassVar[bool] = False
    """If True, render the usage string as markup."""
    
    help_markup: ClassVar[bool] = True
    """If True, render argument help messages as console markup."""
    
    text_markup: ClassVar[bool] = True
    """If True, render descriptions and epilog as console markup."""
    
    def __init__(
        self,
        prog: str,
        indent_increment: int = 2,
        max_help_position: int = 24,
        width: int | None = None,
        *,
        console: Console | None = None,
        **kwargs
    ) -> None:
        """
        Initialize the rich help formatter.
        
        Args:
            prog: Program name
            indent_increment: Number of spaces for each indentation level
            max_help_position: Maximum position for help text alignment
            width: Maximum width for formatting (None for auto-detect)
            console: Rich console instance (None for default)
            **kwargs: Additional arguments passed to parent HelpFormatter
        """

Usage Examples

Basic usage with custom styles:

import argparse
from rich_argparse import RichHelpFormatter

# Customize colors
RichHelpFormatter.styles["argparse.args"] = "bold blue"
RichHelpFormatter.styles["argparse.help"] = "dim"

parser = argparse.ArgumentParser(
    prog="myapp",
    description="A sample application with custom colors",
    formatter_class=RichHelpFormatter
)

Custom group name formatting:

# Custom group name formatter
RichHelpFormatter.group_name_formatter = str.upper

parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)
group = parser.add_argument_group("advanced options")  # Will show as "ADVANCED OPTIONS"

Disable highlighting:

# Turn off text highlighting
RichHelpFormatter.highlights.clear()

parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)

RawDescriptionRichHelpFormatter

Preserves raw description formatting without processing the description text, similar to argparse.RawDescriptionHelpFormatter but with rich styling.

class RawDescriptionRichHelpFormatter(RichHelpFormatter):
    """Rich help message formatter which retains the raw description."""

Usage Examples

import argparse
from rich_argparse import RawDescriptionRichHelpFormatter

parser = argparse.ArgumentParser(
    description="""
    This description preserves:
    - Line breaks
    - Indentation  
    - Spacing
    """,
    formatter_class=RawDescriptionRichHelpFormatter
)

RawTextRichHelpFormatter

Preserves raw formatting for all text elements (description, epilog, and argument help), similar to argparse.RawTextHelpFormatter but with rich styling.

class RawTextRichHelpFormatter(RawDescriptionRichHelpFormatter):
    """Rich help message formatter which retains raw formatting of all help text."""

Usage Examples

import argparse
from rich_argparse import RawTextRichHelpFormatter

parser = argparse.ArgumentParser(
    description="""Raw description with
    preserved formatting""",
    epilog="""Raw epilog with
    preserved formatting""",
    formatter_class=RawTextRichHelpFormatter
)

parser.add_argument("--input", help="""Raw help text with
    preserved formatting""")

ArgumentDefaultsRichHelpFormatter

Shows default values in argument help text, combining argparse.ArgumentDefaultsHelpFormatter with rich formatting.

class ArgumentDefaultsRichHelpFormatter(argparse.ArgumentDefaultsHelpFormatter, RichHelpFormatter):
    """Rich help message formatter which adds default values to argument help."""

Usage Examples

import argparse
from rich_argparse import ArgumentDefaultsRichHelpFormatter

parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsRichHelpFormatter)

parser.add_argument("--count", type=int, default=10, help="Number of items")
parser.add_argument("--format", default="json", help="Output format")
# Help will show: "Number of items (default: 10)" and "Output format (default: json)"

MetavarTypeRichHelpFormatter

Uses type names as metavars instead of dest names, combining argparse.MetavarTypeHelpFormatter with rich formatting.

class MetavarTypeRichHelpFormatter(argparse.MetavarTypeHelpFormatter, RichHelpFormatter):
    """Rich help message formatter which uses type names for metavars."""

Usage Examples

import argparse
from rich_argparse import MetavarTypeRichHelpFormatter

parser = argparse.ArgumentParser(formatter_class=MetavarTypeRichHelpFormatter)

parser.add_argument("--count", type=int, help="Number of items")
parser.add_argument("--rate", type=float, help="Processing rate")
# Help will show: "--count int" instead of "--count COUNT"
# and "--rate float" instead of "--rate RATE"

HelpPreviewAction

Special action class for generating help preview images or SVG files, useful for documentation and testing.

class HelpPreviewAction(argparse.Action):
    """Action to generate help preview images/SVGs."""
    
    def __init__(
        self,
        option_strings,
        dest,
        *,
        path: str,
        export_kwds: dict | None = None,
        **kwargs
    ):
        """
        Initialize the help preview action.
        
        Args:
            option_strings: Command line option strings
            dest: Destination attribute name
            path: Output file path for preview
            export_kwds: Additional arguments for rich export
            **kwargs: Additional arguments passed to parent Action
        """

Usage Examples

import argparse
from rich_argparse import RichHelpFormatter, HelpPreviewAction
from rich.terminal_theme import DIMMED_MONOKAI

parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)

parser.add_argument(
    "--generate-preview",
    action=HelpPreviewAction,
    path="help-preview.svg",
    export_kwds={"theme": DIMMED_MONOKAI}
)

# Running with --generate-preview will create help-preview.svg

Style Customization

Available Style Keys

# Style keys for argparse formatters
ARGPARSE_STYLE_KEYS = {
    "argparse.args": "Positional arguments and options (e.g., '--help')",
    "argparse.groups": "Group names (e.g., 'positional arguments')", 
    "argparse.help": "Argument help text (e.g., 'show this help message and exit')",
    "argparse.metavar": "Meta variables (e.g., 'FILE' in '--file FILE')",
    "argparse.prog": "Program name in usage (e.g., 'foo' in 'Usage: foo [options]')",
    "argparse.syntax": "Highlighted back-tick quoted text (e.g., '`some text`')",
    "argparse.text": "Descriptions and epilog (e.g., 'A foo program')",
    "argparse.default": "Default values in help (e.g., 'Value' in '(default: Value)')"
}

Highlight Patterns

# Default highlight regex patterns
DEFAULT_HIGHLIGHTS = [
    r"`(?P<syntax>[^`]*)`|(?:^|\s)(?P<args>-{1,2}[\w]+[\w-]*)"
]
# Highlights:
# - Text in backticks with "argparse.syntax" style
# - Command-line options (--option, -o) with "argparse.args" style

Configuration Examples

Global Style Customization

from rich_argparse import RichHelpFormatter

# Customize all instances
RichHelpFormatter.styles.update({
    "argparse.args": "bold cyan",
    "argparse.groups": "bold yellow", 
    "argparse.help": "dim white",
    "argparse.metavar": "bold green"
})

Per-Instance Customization

import argparse
from rich_argparse import RichHelpFormatter

class CustomFormatter(RichHelpFormatter):
    styles = {
        **RichHelpFormatter.styles,
        "argparse.args": "magenta",
        "argparse.groups": "blue"
    }

parser = argparse.ArgumentParser(formatter_class=CustomFormatter)

Rich Console Integration

import argparse
from rich.console import Console
from rich_argparse import RichHelpFormatter

# Use custom console
console = Console(width=120, theme=my_theme)

parser = argparse.ArgumentParser(
    formatter_class=lambda prog: RichHelpFormatter(
        prog, 
        console=console
    )
)

Install with Tessl CLI

npx tessl i tessl/pypi-rich-argparse

docs

argparse-formatters.md

contrib-formatters.md

django-integration.md

index.md

optparse-formatters.md

tile.json