Skip to content

Tables

provide.foundation.formatting.tables

TODO: Add module docstring.

Functions

format_table

format_table(
    headers: list[str],
    rows: list[list[Any]],
    alignment: list[str] | None = None,
) -> str

Format data as ASCII table.

Parameters:

Name Type Description Default
headers list[str]

Column headers

required
rows list[list[Any]]

Data rows

required
alignment list[str] | None

Column alignments ('l', 'r', 'c')

None

Returns:

Type Description
str

Formatted table string

Examples:

>>> headers = ['Name', 'Age']
>>> rows = [['Alice', 30], ['Bob', 25]]
>>> print(format_table(headers, rows))
Name  | Age
------|----
Alice | 30
Bob   | 25
Source code in provide/foundation/formatting/tables.py
def format_table(headers: list[str], rows: list[list[Any]], alignment: list[str] | None = None) -> str:
    """Format data as ASCII table.

    Args:
        headers: Column headers
        rows: Data rows
        alignment: Column alignments ('l', 'r', 'c')

    Returns:
        Formatted table string

    Examples:
        >>> headers = ['Name', 'Age']
        >>> rows = [['Alice', 30], ['Bob', 25]]
        >>> print(format_table(headers, rows))
        Name  | Age
        ------|----
        Alice | 30
        Bob   | 25

    """
    if not headers and not rows:
        return ""

    # Convert all cells to strings
    str_headers = [str(h) for h in headers]
    str_rows = [[str(cell) for cell in row] for row in rows]

    # Calculate column widths
    widths = _calculate_column_widths(str_headers, str_rows)

    # Default alignment
    if alignment is None:
        alignment = ["l"] * len(headers)

    # Format header and separator
    header_line, separator_line = _format_table_header(str_headers, widths, alignment)
    lines = [header_line, separator_line]

    # Format data rows
    for row in str_rows:
        lines.append(_format_table_row(row, widths, alignment))

    return "\n".join(lines)