Skip to content

Commit 97b6c37

Browse files
authored
Merge pull request #268 from baolsen/2023-05-23-dataclass-sep-line
Fix separating line with dataclasses
2 parents 537d7b0 + 0978de5 commit 97b6c37

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

tabulate/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1577,7 +1577,12 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):
15771577
field_names = [field.name for field in dataclasses.fields(rows[0])]
15781578
if headers == "keys":
15791579
headers = field_names
1580-
rows = [[getattr(row, f) for f in field_names] for row in rows]
1580+
rows = [
1581+
[getattr(row, f) for f in field_names]
1582+
if not _is_separating_line(row)
1583+
else row
1584+
for row in rows
1585+
]
15811586

15821587
elif headers == "keys" and len(rows) > 0:
15831588
# keys are column indices

test/test_input.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Test support of the various forms of tabular data."""
22

3-
from tabulate import tabulate
3+
from tabulate import tabulate, SEPARATING_LINE
44
from common import assert_equal, assert_in, raises, skip
55

66
try:
@@ -520,6 +520,28 @@ def test_py37orlater_list_of_dataclasses_headers():
520520
skip("test_py37orlater_list_of_dataclasses_headers is skipped")
521521

522522

523+
def test_py37orlater_list_of_dataclasses_with_separating_line():
524+
"Input: a list of dataclasses with a separating line"
525+
try:
526+
from dataclasses import make_dataclass
527+
528+
Person = make_dataclass("Person", ["name", "age", "height"])
529+
ld = [Person("Alice", 23, 169.5), SEPARATING_LINE, Person("Bob", 27, 175.0)]
530+
result = tabulate(ld, headers="keys")
531+
expected = "\n".join(
532+
[
533+
"name age height",
534+
"------ ----- --------",
535+
"Alice 23 169.5",
536+
"------ ----- --------",
537+
"Bob 27 175",
538+
]
539+
)
540+
assert_equal(expected, result)
541+
except ImportError:
542+
skip("test_py37orlater_list_of_dataclasses_keys is skipped")
543+
544+
523545
def test_list_bytes():
524546
"Input: a list of bytes. (issue #192)"
525547
lb = [["你好".encode()], ["你好"]]

0 commit comments

Comments
 (0)