From 0978de5bb3a72d9b285d0e305aaf4574e9ffd5bd Mon Sep 17 00:00:00 2001 From: Bjorn Olsen Date: Tue, 23 May 2023 21:55:13 +0200 Subject: [PATCH] Fix separating line with dataclasses --- tabulate/__init__.py | 7 ++++++- test/test_input.py | 24 +++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb865..f95da8e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1461,7 +1461,12 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): field_names = [field.name for field in dataclasses.fields(rows[0])] if headers == "keys": headers = field_names - rows = [[getattr(row, f) for f in field_names] for row in rows] + rows = [ + [getattr(row, f) for f in field_names] + if not _is_separating_line(row) + else row + for row in rows + ] elif headers == "keys" and len(rows) > 0: # keys are column indices diff --git a/test/test_input.py b/test/test_input.py index a178bd9..d52f10b 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -1,6 +1,6 @@ """Test support of the various forms of tabular data.""" -from tabulate import tabulate +from tabulate import tabulate, SEPARATING_LINE from common import assert_equal, assert_in, raises, skip try: @@ -520,6 +520,28 @@ def test_py37orlater_list_of_dataclasses_headers(): skip("test_py37orlater_list_of_dataclasses_headers is skipped") +def test_py37orlater_list_of_dataclasses_with_separating_line(): + "Input: a list of dataclasses with a separating line" + try: + from dataclasses import make_dataclass + + Person = make_dataclass("Person", ["name", "age", "height"]) + ld = [Person("Alice", 23, 169.5), SEPARATING_LINE, Person("Bob", 27, 175.0)] + result = tabulate(ld, headers="keys") + expected = "\n".join( + [ + "name age height", + "------ ----- --------", + "Alice 23 169.5", + "------ ----- --------", + "Bob 27 175", + ] + ) + assert_equal(expected, result) + except ImportError: + skip("test_py37orlater_list_of_dataclasses_keys is skipped") + + def test_list_bytes(): "Input: a list of bytes. (issue #192)" lb = [["你好".encode("utf-8")], ["你好"]]