From 0a4626cb0cb0f1ceea4e7484d856f45783bfca83 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Mon, 23 Nov 2026 21:54:44 +0800 Subject: [PATCH] Add footer rows with shared numeric formatting and column alignment --- README.md | 27 +++++ tabulate/__init__.py | 134 +++++++++++++++++------- test/test_api.py | 1 + test/test_footer.py | 242 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 368 insertions(+), 36 deletions(-) create mode 100644 test/test_footer.py diff --git a/README.md b/README.md index 0283a0c..da47f36 100644 --- a/README.md +++ b/README.md @@ -1102,6 +1102,33 @@ linebetweenrows, linebelowheader, linebelow, lineabove or just a simple empty li Moon 1737 ----- ---- +### Footer or total row + +Pass `footer` to display one summary row after the table body. Supply one +cell per data column, in the same column order as the input; totals are +calculated by the caller. Footer values participate in numeric type +inference, formatting, column widths, alignment and text wrapping just like +body cells. + +```python +>>> print(tabulate([["A", 1.25], ["B", 2.5]], headers=["Item", "Cost"], +... footer=["Total", 3.75], floatfmt=".2f")) +Item Cost +------ ------ +A 1.25 +B 2.50 +------ ------ +Total 3.75 + +``` + +The footer is separated by the table format's header rule, or a blank line +in formats without rules. HTML output uses a `tfoot` section. A footer can +also be used with an empty body. If row indices are shown, the footer's +index cell is blank; custom index iterables contain entries for body rows +only. The last entry of a per-row `rowalign` list can set footer alignment. +`footer=None` keeps the usual output without a footer. + ### ANSI support ANSI escape codes are non-printable byte sequences usually used for terminal operations like setting color output or modifying cursor positions. Because multi-byte ANSI sequences are inherently non-printable, diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..04fb7a1 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1425,7 +1425,7 @@ def _bool(val): return False -def _normalize_tabular_data(tabular_data, headers, showindex="default"): +def _normalize_tabular_data(tabular_data, headers, showindex="default", footer=None): """Transform a supported data type to a list of lists, and a list of headers, with headers padding. @@ -1589,21 +1589,52 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): # rows = list(map(list, rows)) rows = [r if _is_separating_line(r) else list(r) for r in rows] + if footer is not None: + if isinstance(footer, (str, bytes, dict)): + raise TypeError("footer must be an iterable of cell values") + footer = list(footer) + if not footer or _is_separating_line(footer): + raise ValueError( + "footer must contain at least one cell and cannot be a separating line" + ) + column_count = max( + (len(row) for row in rows if not _is_separating_line(row)), + default=len(tabular_data.columns) if index is not None else len(headers), + ) + if column_count and len(footer) != column_count: + raise ValueError( + "footer must have one cell per data column: " + f"len(footer)={len(footer)} columns={column_count}" + ) + # add or remove an index column showindex_is_a_str = type(showindex) in [str, bytes] + index_added = False if showindex_is_a_str and showindex == "default" and index is not None: rows = _prepend_row_index(rows, index) + index_added = True elif isinstance(showindex, Sized) and not showindex_is_a_str: rows = _prepend_row_index(rows, list(showindex)) + index_added = True elif isinstance(showindex, Iterable) and not showindex_is_a_str: rows = _prepend_row_index(rows, showindex) + index_added = True elif showindex == "always" or (_bool(showindex) and not showindex_is_a_str): if index is None: index = list(range(len(rows))) rows = _prepend_row_index(rows, index) + index_added = True elif showindex == "never" or (not _bool(showindex) and not showindex_is_a_str): pass + if footer is not None: + footer = ([""] if index_added else []) + footer + rows = [ + row if _is_separating_line(row) else row + [None] * (len(footer) - len(row)) + for row in rows + ] + rows.append(footer) + # pad with empty headers for initial columns if necessary headers_pad = 0 if headers and len(rows) > 0: @@ -1714,6 +1745,7 @@ def tabulate( maxheadercolwidths=None, break_long_words=_BREAK_LONG_WORDS, break_on_hyphens=_BREAK_ON_HYPHENS, + footer=None, ): """Format a fixed width table for pretty printing. @@ -2232,13 +2264,19 @@ def tabulate( Header column width can be specified in a similar way using `maxheadercolwidths`. + `footer` is an optional, non-empty iterable with one cell per data column. + It participates in type inference, numeric formatting, wrapping and alignment. + Its index cell is blank when a row index is shown. It is separated from the + body with the format's header rule (or a blank line for ruleless formats). + HTML uses a `tfoot` element. No totals are computed automatically. + """ if tabular_data is None: tabular_data = [] list_of_lists, headers, headers_pad = _normalize_tabular_data( - tabular_data, headers, showindex=showindex + tabular_data, headers, showindex=showindex, footer=footer ) list_of_lists, separating_lines = _remove_separating_lines(list_of_lists) @@ -2448,6 +2486,8 @@ def tabulate( ra_default = rowalign if isinstance(rowalign, str) else None rowaligns = _expand_iterable(rowalign, len(rows), ra_default) + footer_row = rows.pop() if footer is not None else None + footeralign = rowaligns.pop() if footer is not None else None _reinsert_separating_lines(rows, separating_lines) return _format_table( @@ -2459,6 +2499,8 @@ def tabulate( aligns, is_multiline, rowaligns=rowaligns, + footer=footer_row, + footeralign=footeralign, ) @@ -2610,7 +2652,16 @@ def str(self): def _format_table( - fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns + fmt, + headers, + headersaligns, + rows, + colwidths, + colaligns, + is_multiline, + rowaligns, + footer=None, + footeralign=None, ): """Produce a plain-text representation of the table.""" lines = [] @@ -2636,48 +2687,59 @@ def _format_table( if fmt.linebelowheader and "linebelowheader" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelowheader) - if rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: - # initial rows with a line below - for row, ralign in zip(rows[:-1], rowaligns): - if row != SEPARATING_LINE: - append_row( - lines, - pad_row(row, pad), - padded_widths, - colaligns, - fmt.datarow, - rowalign=ralign, - ) - _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) - # the last row without a line below + # An explicit trailing separator is replaced by the footer's own boundary. + if footer is not None: + while rows and _is_separating_line(rows[-1]): + rows.pop() + + between_rows = fmt.linebetweenrows and "linebetweenrows" not in hidden + separating_line = ( + fmt.linebetweenrows + or fmt.linebelowheader + or fmt.linebelow + or fmt.lineabove + or Line("", "", "", "") + ) + align_iter = iter(rowaligns) + for index, row in enumerate(rows): + if _is_separating_line(row): + _append_line(lines, padded_widths, colaligns, separating_line) + else: + append_row( + lines, + pad_row(row, pad), + padded_widths, + colaligns, + fmt.datarow, + rowalign=next(align_iter, None), + ) + if between_rows and index < len(rows) - 1: + _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) + + is_html = fmt.lineabove == _html_begin_table_without_header + if footer is not None: + if is_html: + lines.append("\n") + elif rows: + footer_line = fmt.linebelowheader or fmt.linebetweenrows or Line("", "", "", "") + if fmt == _table_formats["latex_longtable"]: + footer_line = Line("\\hline", "", "", "") + _append_line(lines, padded_widths, colaligns, footer_line) append_row( lines, - pad_row(rows[-1], pad), + pad_row(footer, pad), padded_widths, colaligns, fmt.datarow, - rowalign=rowaligns[-1], + rowalign=footeralign, ) - else: - separating_line = ( - fmt.linebetweenrows - or fmt.linebelowheader - or fmt.linebelow - or fmt.lineabove - or Line("", "", "", "") - ) - for row in rows: - # test to see if either the 1st column or the 2nd column (account for showindex) has - # the SEPARATING_LINE flag - if _is_separating_line(row): - _append_line(lines, padded_widths, colaligns, separating_line) - else: - append_row(lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow) - if fmt.linebelow and "linebelow" not in hidden: + if is_html and footer is not None: + lines.append("\n") + elif fmt.linebelow and "linebelow" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelow) - if headers or rows: + if headers or rows or footer is not None: output = "\n".join(lines) if fmt.lineabove == _html_begin_table_without_header: return JupyterHTMLStr(output) diff --git a/test/test_api.py b/test/test_api.py index cb59836..3d617ea 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -56,6 +56,7 @@ def test_tabulate_signature(): ("maxheadercolwidths", None), ("break_long_words", True), ("break_on_hyphens", True), + ("footer", None), ] _check_signature(tabulate, expected_sig) diff --git a/test/test_footer.py b/test/test_footer.py new file mode 100644 index 0000000..f7f2b5a --- /dev/null +++ b/test/test_footer.py @@ -0,0 +1,242 @@ +"""Footer rows share the body formatting pipeline and have a distinct boundary.""" + +from copy import deepcopy +from decimal import Decimal +from xml.etree import ElementTree + +import pytest + +from tabulate import SEPARATING_LINE, simple_separated_format, tabulate, tabulate_formats + + +def test_total_formats_like_body_and_expands_width(): + assert tabulate( + [["A", 1.25], ["B", 2.5]], + headers=["Item", "Cost"], + footer=["Total", 3.75], + floatfmt=".2f", + ) == "\n".join( + [ + "Item Cost", + "------ ------", + "A 1.25", + "B 2.50", + "------ ------", + "Total 3.75", + ] + ) + + +def test_footer_can_widen_the_numeric_column_and_infer_float(): + assert tabulate( + [[1]], footer=[Decimal("123456789.125")], floatfmt=".3f", tablefmt="plain" + ) == (" 1.000\n\n123456789.125") + + +@pytest.mark.parametrize( + "showindex", [True, "always", ["first", "second"], iter(["first", "second"])] +) +def test_footer_does_not_consume_an_index(showindex): + result = tabulate( + [["A", 1], ["B", 2]], + headers=["item", "n"], + footer=["Total", 3], + showindex=showindex, + tablefmt="tsv", + ) + assert result.splitlines()[-1].split("\t")[0].strip() == "" + assert result.splitlines()[-1].split("\t")[1].strip() == "Total" + assert result.count("Total") == 1 + + +def test_firstrow_headers_do_not_come_from_footer(): + assert tabulate( + [["name", "value"], ["A", 1.0]], headers="firstrow", footer=["Total", 1.0] + ) == ("name value\n------ -------\nA 1\n------ -------\nTotal 1") + + +def test_dictionary_columns_and_mapped_headers(): + result = tabulate( + [{"name": "A", "value": 1.25}], + headers={"name": "Item", "value": "Cost"}, + footer=["Total", 1.25], + floatfmt=".2f", + ) + assert result.splitlines()[-1] == "Total 1.25" + assert result.splitlines()[0] == "Item Cost" + + +def test_generators_are_consumed_once_and_inputs_are_not_mutated(): + rows = [["A", 1.25], ["B", 2.5]] + footer = ["Total", 3.75] + original = deepcopy((rows, footer)) + result = tabulate((row for row in rows), footer=(value for value in footer), tablefmt="grid") + assert (rows, footer) == original + assert result.count("Total") == 1 + + +@pytest.mark.parametrize("tablefmt", tabulate_formats) +def test_footer_none_preserves_output(tablefmt): + rows = [["A", 1.25], ["B", 2.5]] + assert tabulate(rows, headers=["item", "cost"], tablefmt=tablefmt, footer=None) == tabulate( + rows, + headers=["item", "cost"], + tablefmt=tablefmt, + ) + + +@pytest.mark.parametrize("tablefmt", tabulate_formats) +def test_footer_available_in_every_builtin_format(tablefmt): + result = tabulate( + [["A", 1.5]], + headers=["Item", "Cost"], + footer=["TOTAL", 1.5], + floatfmt=".2f", + tablefmt=tablefmt, + ) + assert result.count("TOTAL") == 1 + assert "1.50" in result or tablefmt == "pretty" + assert SEPARATING_LINE not in result + + +@pytest.mark.parametrize("rows, headers", [([], ()), (None, ()), ([], ["item", "cost"])]) +def test_footer_only(rows, headers): + result = tabulate( + rows, headers=headers, footer=["Total", 0.0], tablefmt="grid", floatfmt=".2f" + ) + assert "| Total" in result and "0.00 |" in result + assert result.count("Total") == 1 + + +def test_footer_only_with_index(): + assert ( + tabulate([], headers=["item", "n"], footer=["Total", 0], showindex=True, tablefmt="tsv") + .splitlines()[-1] + .split("\t")[0] + .strip() + == "" + ) + + +def test_footer_precision_missing_values_and_int_format(): + result = tabulate( + [["A", 1000, Decimal("1.0000000000000001"), None]], + footer=["Total", 1000, Decimal("1.0000000000000001"), None], + floatfmt=".16f", + intfmt=",d", + missingval="?", + tablefmt="plain", + ) + assert result.splitlines()[-1] == "Total 1,000 1.0000000000000001 ?" + + +def test_numeric_strings_are_not_parsed_when_disabled(): + result = tabulate( + [["A", "01.20"]], + footer=["Total", "01.20"], + disable_numparse=True, + floatfmt=".1f", + tablefmt="plain", + ) + assert result.splitlines()[-1] == "Total 01.20" + + +def test_multiline_footer_and_vertical_alignment(): + result = tabulate( + [["A", 1.0]], + footer=["Grand\nTotal", 1.0], + tablefmt="grid", + floatfmt=".2f", + rowalign=["top", "bottom"], + ) + assert result.splitlines()[-3:] == [ + "| Grand | |", + "| Total | 1.00 |", + "+-------+------+", + ] + + +def test_footer_wraps_using_body_width_configuration(): + result = tabulate( + [["A", 1]], footer=["Grand Total", 1], tablefmt="grid", maxcolwidths=[5, None] + ) + assert result.splitlines()[-3:] == [ + "| Grand | 1 |", + "| Total | |", + "+-------+---+", + ] + + +def test_ansi_footer_uses_visible_width(): + options = {"headers": ["Item", "Cost"], "tablefmt": "grid", "floatfmt": ".1f"} + result = tabulate([["A", 1.5]], footer=["\x1b[31mTotal\x1b[0m", 1.5], **options) + assert result.replace("\x1b[31m", "").replace("\x1b[0m", "") == tabulate( + [["A", 1.5]], + footer=["Total", 1.5], + **options, + ) + + +@pytest.mark.parametrize("tablefmt", ["simple", "grid"]) +def test_existing_separators_do_not_consume_rows_or_duplicate_footer_rule(tablefmt): + rows = [["A", 1], SEPARATING_LINE, ["B", 2], ["C", 3], SEPARATING_LINE] + result = tabulate(rows, footer=["Total", 6], tablefmt=tablefmt) + assert all(label in result for label in ["A", "B", "C", "Total"]) + lines = result.splitlines() + footer_at = next(i for i, line in enumerate(lines) if "Total" in line) + assert "C" in lines[footer_at - 2] + + +@pytest.mark.parametrize("tablefmt", ["html", "unsafehtml"]) +def test_html_footer_is_a_separate_section_inside_one_table(tablefmt): + result = tabulate( + [["A", 1.5]], + headers=["Item", "Cost"], + footer=["Total", 1.5], + tablefmt=tablefmt, + floatfmt=".2f", + ) + table = ElementTree.fromstring(result) + assert [child.tag for child in table] == ["thead", "tbody", "tfoot"] + assert [cell.text.strip() for cell in table.findall("./tfoot/tr/td")] == ["Total", "1.50"] + assert len(table.findall("./tbody/tr")) == 1 + assert hasattr(result, "_repr_html_") + + +def test_longtable_does_not_repeat_endhead_before_footer(): + result = tabulate( + [["A", 1]], headers=["Item", "n"], footer=["Total", 1], tablefmt="latex_longtable" + ) + assert result.count("\\endhead") == 1 + assert result.count("\\end{longtable}") == 1 + assert "Total" in result.split("\\endhead")[1].split("\\end{longtable}")[0] + + +def test_custom_ruleless_format(): + assert tabulate([["A", 1]], footer=["Total", 1], tablefmt=simple_separated_format(";")) == ( + "A ;1\n\nTotal;1" + ) + + +@pytest.mark.parametrize("footer", [[], ["one"], [1, 2, 3], SEPARATING_LINE, "total", {"a": 1}]) +def test_invalid_footer_is_rejected(footer): + with pytest.raises((ValueError, TypeError), match="footer"): + tabulate([["A", 1]], footer=footer) + + +def test_pandas_index_is_blank_in_footer_including_empty_frame(): + pd = pytest.importorskip("pandas") + for frame in [ + pd.DataFrame({"cost": [1.5]}, index=pd.Index(["a"], name="id")), + pd.DataFrame({"cost": []}, index=pd.Index([], name="id")), + ]: + result = tabulate(frame, headers="keys", footer=[1.5], floatfmt=".2f", tablefmt="tsv") + assert [cell.strip() for cell in result.splitlines()[-1].split("\t")] == ["", "1.50"] + + +def test_ragged_body_is_padded_before_wrapping_footer(): + result = tabulate( + [["A"], ["B", 1]], footer=["Grand Total", 1], maxcolwidths=[5, None], tablefmt="grid" + ) + assert "| Grand | 1 |" in result + assert "| Total | |" in result