diff --git a/README.md b/README.md index 0283a0c..31aec94 100644 --- a/README.md +++ b/README.md @@ -766,6 +766,26 @@ column, in which case every column may have different number formatting: ``` +For custom formats, `floatfmt` also accepts a callable, or a mixture of +callables and format strings in its per-column list. The callable receives +a `float`, except that `Decimal` values are passed through unchanged to +preserve their precision, and must return a string. For example, engineering +notation can be produced with `Decimal.to_eng_string`: + +```python +>>> from decimal import Decimal +>>> print(tabulate([[Decimal("1E-7")]], floatfmt=Decimal.to_eng_string, tablefmt="plain")) +100E-9 + +``` + +Callables follow the same column type inference as format strings: they +apply to floating-point columns, including parsed numeric strings, and do +not apply to integer or text columns. `None` and empty strings bypass the +callable. Returned text is not parsed again; normal alignment still applies. +ANSI colors and multiline results are supported by the corresponding table +formats. Exceptions raised by a callable propagate to the caller. + `intfmt` works similarly for integers >>> print(tabulate([["a",1000],["b",90000]], intfmt=",")) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..22092f8 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1091,7 +1091,7 @@ def _strip_ansi(s): if isinstance(s, str): return _ansi_codes.sub(r"\4", s) else: # a bytestring - return _ansi_codes_bytes.sub(r"\4", s) + return _ansi_codes_bytes.sub(rb"\4", s) def _visible_width(s): @@ -1299,6 +1299,22 @@ def _column_type(strings, has_invisible=True, numparse=True): return reduce(_more_generic, types, bool) +def _format_float_callable(val, formatter, has_invisible): + """Convert a numeric cell before calling user code, preserving Decimal precision.""" + text = _to_str(val) if isinstance(val, (str, bytes)) else None + raw = _strip_ansi(text) if text is not None and has_invisible else text + try: + number = val if isinstance(val, Decimal) else float(raw.replace(",", "") if raw else val) + except (ValueError, TypeError): + return _to_str(val) + + # Formatter errors belong to the caller and must not be treated as parse failures. + result = formatter(number) + if not isinstance(result, str): + raise TypeError("floatfmt callable must return a string") + return text.replace(raw, result) if text is not None and raw != text else result + + def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): """Format a value according to its deduced type. Empty values are deemed valid for any type. @@ -1337,6 +1353,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): except (TypeError, UnicodeDecodeError): return str(val) elif valtype is float: + if callable(floatfmt): + return _format_float_callable(val, floatfmt, has_invisible) is_a_colored_number = has_invisible and isinstance(val, (str, bytes)) if is_a_colored_number: raw_val = _strip_ansi(val) @@ -1801,9 +1819,11 @@ def tabulate( contain numeric data without a decimal point. This can also be a list or tuple of format strings, one per column. - `floatfmt` is a format specification used for columns which - contain numeric data with a decimal point. This can also be - a list or tuple of format strings, one per column. + `floatfmt` is a format specification or callable used for columns + which contain numeric data with a decimal point. This can also be + a list or tuple of strings and callables, one per column. A callable + receives a float (or the original Decimal) and must return a string. + Missing values bypass the callable; its exceptions propagate. `None` values are replaced with a `missingval` string (like `floatfmt`, this can also be a list of values for different @@ -2334,14 +2354,12 @@ def tabulate( is_multiline = True else: is_multiline = False - width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline) - # format rows and columns, convert numeric values to strings cols = list(izip_longest(*list_of_lists)) numparses = _expand_numparse(disable_numparse, len(cols)) coltypes = [_column_type(col, numparse=np) for col, np in zip(cols, numparses)] - if isinstance(floatfmt, str): # old version - float_formats = len(cols) * [floatfmt] # just duplicate the string to use in each column + if isinstance(floatfmt, str) or callable(floatfmt): + float_formats = len(cols) * [floatfmt] else: # if floatfmt is list, tuple etc we have one per column float_formats = list(floatfmt) if len(float_formats) < len(cols): @@ -2365,6 +2383,20 @@ def tabulate( ) ] + if any(callable(fmt) for fmt in float_formats): + # A formatter may introduce control codes or line breaks absent from the input. + formatted_text = "\t".join(chain.from_iterable(cols)) + has_invisible = has_invisible or _ansi_codes.search(formatted_text) is not None + if ( + not is_multiline + and not isinstance(tablefmt, TableFormat) + and tablefmt in multiline_formats + and _is_multiline(formatted_text) + ): + tablefmt = multiline_formats[tablefmt] + is_multiline = True + width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline) + # align columns # first set global alignment if colglobalalign is not None: # if global alignment provided diff --git a/test/test_callable_floatfmt.py b/test/test_callable_floatfmt.py new file mode 100644 index 0000000..b4c31ef --- /dev/null +++ b/test/test_callable_floatfmt.py @@ -0,0 +1,166 @@ +"""Custom numeric formatting through the public table API.""" + +from decimal import Decimal +import math + +import pytest + +import tabulate as tabulate_module +from tabulate import SEPARATING_LINE, tabulate + + +def test_engineering_notation_is_not_reparsed(): + assert ( + tabulate( + [[Decimal("1E-7")], [Decimal("1E6")]], + floatfmt=Decimal.to_eng_string, + tablefmt="plain", + numalign=None, + ) + == "100E-9\n1E+6" + ) + + +def test_per_column_callable_and_format_strings(): + assert ( + tabulate( + [[1.25, 2.75, 3.5]], + floatfmt=(lambda value: f"<{value}>", ".1f"), + tablefmt="plain", + ) + == "<1.25> 2.8 3.5" + ) + + +def test_decimal_keeps_precision_and_identity(): + value = Decimal("99999998999.9999800000001") + seen = [] + + def formatter(number): + seen.append(number) + return str(number) + + assert tabulate([[value]], floatfmt=formatter, tablefmt="plain") == str(value) + assert seen == [value] + assert seen[0] is value + + +def test_type_inference_and_missing_cells(): + seen = [] + + def formatter(number): + seen.append(number) + return f"{number:.1f}" + + result = tabulate( + [["text", 1, 2.5], ["more", 2, None], ["last", 3, ""]], + floatfmt=formatter, + missingval="?", + tablefmt="plain", + ) + assert result == "text 1 2.5\nmore 2 ?\nlast 3" + assert seen == [2.5] + + +def test_disable_numparse_does_not_format_numeric_strings(): + seen = [] + assert ( + tabulate( + [["2.50", 1.5]], + floatfmt=lambda value: seen.append(value) or "formatted", + disable_numparse=[0], + tablefmt="plain", + ) + == "2.50 formatted" + ) + assert seen == [1.5] + + +@pytest.mark.parametrize("value", [1.25, "1.25", b"1.25", "1,000.25"]) +def test_callback_gets_parsed_float(value): + seen = [] + tabulate([[value]], floatfmt=lambda number: seen.append(number) or "number") + assert seen == [1000.25 if value == "1,000.25" else 1.25] + assert type(seen[0]) is float + + +def test_callable_object(): + class Formatter: + def __call__(self, number): + return f"{number * 100:.0f}%" + + assert tabulate([[0.125]], floatfmt=Formatter(), tablefmt="plain") == "12%" + + +def test_nonfinite_values_and_negative_zero(): + seen = [] + tabulate( + [[math.inf], [-math.inf], [math.nan], [-0.0]], floatfmt=lambda x: seen.append(x) or str(x) + ) + assert seen[:2] == [math.inf, -math.inf] + assert math.isnan(seen[2]) + assert math.copysign(1, seen[3]) == -1 + + +@pytest.mark.parametrize("error_type", [ValueError, TypeError, RuntimeError]) +def test_callback_exception_propagates(error_type): + error = error_type("custom formatting failed") + + def formatter(number): + raise error + + with pytest.raises(error_type) as caught: + tabulate([[1.5]], floatfmt=formatter) + assert caught.value is error + + +@pytest.mark.parametrize("result", [None, 3, b"1.50"]) +def test_callback_must_return_string(result): + with pytest.raises(TypeError, match="floatfmt callable must return a string"): + tabulate([[1.5]], floatfmt=lambda value: result) + + +@pytest.mark.parametrize("value", ["\x1b[31m1.25\x1b[0m", b"\x1b[31m1.25\x1b[0m"]) +def test_colored_numeric_input(value): + assert tabulate([[value]], floatfmt=lambda number: f"{number:.1f}", tablefmt="plain") == ( + "\x1b[31m1.2\x1b[0m" + ) + + +@pytest.mark.parametrize("widechars", [False, True]) +def test_output_colors_do_not_change_column_width(widechars, monkeypatch): + monkeypatch.setattr(tabulate_module, "WIDE_CHARS_MODE", widechars) + data = [[1.25], [20.5]] + plain = tabulate(data, headers=["value"], tablefmt="grid", floatfmt=".2f") + colored = tabulate( + data, + headers=["value"], + tablefmt="grid", + floatfmt=lambda value: f"\x1b[31m{value:.2f}\x1b[0m", + ) + assert colored.replace("\x1b[31m", "").replace("\x1b[0m", "") == plain + + +@pytest.mark.parametrize("tablefmt", ["grid", "simple", "plain"]) +def test_callback_can_introduce_multiline_cells(tablefmt): + options = {"headers": ["value"], "tablefmt": tablefmt, "colalign": ("right",)} + assert tabulate( + [[1.5], [12.0]], floatfmt=lambda value: f"{value:.1f}\nunits", **options + ) == tabulate([["1.5\nunits"], ["12.0\nunits"]], disable_numparse=True, **options) + + +def test_missing_blank_and_separator_rows_do_not_call_formatter(): + seen = [] + result = tabulate( + [[1.5], [None], [""], SEPARATING_LINE, [2.5]], + floatfmt=lambda value: seen.append(value) or f"{value:.1f}", + tablefmt="simple", + missingval="?", + numalign=None, + ) + assert seen == [1.5, 2.5] + assert "?" in result and "2.5" in result + + +def test_empty_table_with_callable(): + assert tabulate([], floatfmt=lambda value: pytest.fail("empty table")) == ""