Typing stubs for click - a command line interface creation kit for Python
Text formatting utilities for creating well-structured help output, text wrapping, and table formatting. These functions are primarily used internally by Click but can be useful for custom help formatting and output generation.
Core class for formatting help text with proper indentation, sections, and layout.
class HelpFormatter:
indent_increment: int
width: int | None
current_indent: int
buffer: list[str]
def __init__(
self,
indent_increment: int = 2,
width: int | None = None,
max_width: int | None = None
) -> None:
"""
Create a help formatter.
Parameters:
- indent_increment: Spaces per indent level
- width: Target width for output
- max_width: Maximum width for output
"""
def write(self, string: str) -> None:
"""
Write text to the formatter buffer.
Parameters:
- string: Text to write
"""
def indent(self) -> None:
"""Increase indentation level."""
def dedent(self) -> None:
"""Decrease indentation level."""
def write_usage(self, prog: str, args: str = '', prefix: str = 'Usage: ') -> None:
"""
Write a usage line.
Parameters:
- prog: Program name
- args: Arguments string
- prefix: Usage prefix text
"""
def write_heading(self, heading: str) -> None:
"""
Write a section heading.
Parameters:
- heading: Heading text
"""
def write_paragraph(self) -> None:
"""Write a paragraph break."""
def write_text(self, text: str) -> None:
"""
Write wrapped text.
Parameters:
- text: Text to write and wrap
"""
def write_dl(
self,
rows: Iterable[Iterable[str]],
col_max: int = 30,
col_spacing: int = 2
) -> None:
"""
Write a definition list (two-column layout).
Parameters:
- rows: Iterable of rows, each containing (term, definition)
- col_max: Maximum width for first column
- col_spacing: Spacing between columns
"""
def section(self, name: str) -> ContextManager[None]:
"""
Context manager for a formatted section.
Parameters:
- name: Section name
Usage:
formatter = HelpFormatter()
with formatter.section('Options'):
formatter.write_text('Available options:')
formatter.write_dl([('--help', 'Show help message')])
"""
def indentation(self) -> ContextManager[None]:
"""
Context manager for temporary indentation.
Usage:
formatter = HelpFormatter()
formatter.write('Normal text')
with formatter.indentation():
formatter.write('Indented text')
formatter.write('Normal text again')
"""
def getvalue(self) -> str:
"""
Get the formatted output.
Returns:
Complete formatted text
"""Functions for wrapping and formatting text content.
def wrap_text(
text: str,
width: int = 78,
initial_indent: str = '',
subsequent_indent: str = '',
preserve_paragraphs: bool = False,
) -> str:
"""
Wrap text to specified width with indentation control.
Parameters:
- text: Text to wrap
- width: Target line width
- initial_indent: Indent for first line
- subsequent_indent: Indent for continuation lines
- preserve_paragraphs: Keep paragraph breaks
Returns:
Wrapped text string
Usage:
# Basic wrapping
wrapped = click.formatting.wrap_text('Long text...', width=60)
# With indentation
wrapped = click.formatting.wrap_text(
'Long help text...',
width=70,
initial_indent=' ',
subsequent_indent=' '
)
# Preserve paragraphs
wrapped = click.formatting.wrap_text(
'Para 1\\n\\nPara 2',
preserve_paragraphs=True
)
"""Functions for measuring and formatting tabular data.
def measure_table(rows: Iterable[Iterable[str]]) -> tuple[int, ...]:
"""
Measure column widths for a table.
Parameters:
- rows: Table rows as iterables of strings
Returns:
Tuple of maximum widths for each column
Usage:
table_data = [
['Name', 'Age', 'City'],
['Alice', '25', 'New York'],
['Bob', '30', 'San Francisco']
]
widths = click.formatting.measure_table(table_data)
# widths = (5, 3, 13)
"""
def iter_rows(
rows: Iterable[Iterable[str]],
col_count: int
) -> Generator[tuple[str, ...], None, None]:
"""
Iterate table rows, ensuring consistent column count.
Parameters:
- rows: Table rows as iterables of strings
- col_count: Expected number of columns
Yields:
Tuples of strings with consistent column count
Usage:
table_data = [['A', 'B'], ['C']] # Inconsistent columns
for row in click.formatting.iter_rows(table_data, 2):
print(row) # ('A', 'B'), ('C', '')
"""Utilities for formatting command-line options.
def join_options(options: list[str]) -> tuple[str, bool]:
"""
Join option names for display.
Parameters:
- options: List of option strings
Returns:
Tuple of (joined_options, any_prefix_is_long)
Usage:
joined, has_long = click.formatting.join_options(['-v', '--verbose'])
# joined = '-v, --verbose', has_long = True
joined, has_long = click.formatting.join_options(['-h'])
# joined = '-h', has_long = False
"""Configuration constants for formatting behavior.
FORCED_WIDTH: int | None
"""
Global width override for all formatting operations.
When set, overrides automatic width detection.
Usage:
import click.formatting
click.formatting.FORCED_WIDTH = 80 # Force 80-column output
"""from click.formatting import HelpFormatter
def format_custom_help(commands):
formatter = HelpFormatter(width=80)
formatter.write_usage('myapp', '[OPTIONS] COMMAND [ARGS]')
formatter.write_paragraph()
with formatter.section('Available Commands'):
rows = [(name, cmd.get_short_help_str()) for name, cmd in commands.items()]
formatter.write_dl(rows)
return formatter.getvalue()from click.formatting import measure_table, iter_rows
def format_table(data, headers):
all_rows = [headers] + data
widths = measure_table(all_rows)
result = []
for row in iter_rows(all_rows, len(headers)):
formatted_row = ' '.join(
cell.ljust(width) for cell, width in zip(row, widths)
)
result.append(formatted_row)
return '\\n'.join(result)
# Usage
data = [['Alice', '25'], ['Bob', '30']]
headers = ['Name', 'Age']
table = format_table(data, headers)
click.echo(table)from click.formatting import wrap_text
def format_command_help(help_text):
return wrap_text(
help_text,
width=72,
initial_indent=' ',
subsequent_indent=' ',
preserve_paragraphs=True
)
# Usage
help_text = "This is a long help message that needs to be wrapped properly..."
formatted = format_command_help(help_text)
click.echo(formatted)Install with Tessl CLI
npx tessl i tessl/pypi-types-click