Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,26 @@ The following tabular data types are supported:
- list or another iterable of dicts (keys as columns)
- dict of iterables (keys as columns)
- list of dataclasses (field names as columns)
- list or another iterable of Pydantic models (serialized field names as columns)
- two-dimensional NumPy array
- NumPy record arrays (names as columns)
- pandas.DataFrame
- polars.DataFrame (column names as headers with `headers="keys"`)

Tabulate is a Python3 library.

Polars frames use their row iterator and have no implicit row index. Empty
frames retain their column names with `headers="keys"`; `showindex="always"`
adds a numbered index as it does for ordinary rows. Lazy frames must be
collected explicitly before calling `tabulate`.

Pydantic models use `model_dump()` (version 2) or `dict()` (version 1), preserving
their field exclusions and custom serializers. They follow the same header
rules as lists of dictionaries, including header mappings, and fields from
different model classes are combined in encounter order. Version 2 `RootModel`
values occupy a single `root` column. Neither library is required to import or
use `tabulate` with other inputs.

### Headers

The second optional argument named `headers` defines a list of column
Expand Down
36 changes: 33 additions & 3 deletions tabulate/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Pretty-print tabular data."""

from collections import namedtuple
from collections.abc import Callable, Iterable, Sized
from collections.abc import Callable, Iterable, Mapping, Sized
import dataclasses
from dataclasses import dataclass
from decimal import Decimal
Expand Down Expand Up @@ -1425,6 +1425,21 @@ def _bool(val):
return False


def _model_to_dict(row):
"""Use Pydantic's public serialization API without importing an optional dependency."""
if hasattr(type(row), "model_fields") and callable(getattr(row, "model_dump", None)):
values = row.model_dump()
# RootModel serializes its value directly, but occupies one table cell.
if getattr(type(row), "__pydantic_root_model__", False):
return {"root": values}
if not isinstance(values, Mapping):
raise TypeError("Pydantic table rows must serialize to a mapping")
return values
if hasattr(type(row), "__fields__") and callable(getattr(row, "dict", None)):
return row.dict() # Pydantic 1.x, including pydantic.v1 compatibility models.
return row


def _normalize_tabular_data(tabular_data, headers, showindex="default"):
"""Transform a supported data type to a list of lists, and a list of headers,
with headers padding.
Expand All @@ -1441,6 +1456,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):

* list of dataclasses (usually used with headers="keys")

* list of Pydantic models (usually used with headers="keys")

* 2D NumPy arrays

* NumPy record arrays (usually used with headers="keys")
Expand All @@ -1449,6 +1466,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):

* pandas.DataFrame (usually used with headers="keys")

* polars.DataFrame (usually used with headers="keys", no implicit row index)

The first row can be used as headers if headers="firstrow",
column indices can be used as headers if headers="keys".

Expand All @@ -1470,7 +1489,12 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):
"\nDid you forget a pair of extra [] or ',' in ()?"
)
index = None
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
if hasattr(tabular_data, "columns") and callable(getattr(tabular_data, "iter_rows", None)):
# Polars exposes rows directly; iterating the frame yields columns.
rows = list(tabular_data.iter_rows())
if headers == "keys":
headers = list(map(str, tabular_data.columns))
elif hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
# dict-like and pandas.DataFrame?
if callable(tabular_data.values):
# likely a conventional dict
Expand Down Expand Up @@ -1504,6 +1528,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):
except TypeError as e: # not iterable
raise TypeError(err_msg) from e

rows = [_model_to_dict(row) for row in rows]

if headers == "keys" and not rows:
# an empty table (issue #81)
headers = []
Expand All @@ -1528,6 +1554,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):
uniq_keys.update(keys)
rows = rows[1:]
for row in rows:
if _is_separating_line(row):
continue
for k in row.keys():
# Save unique items in input order
if k not in uniq_keys:
Expand All @@ -1547,7 +1575,9 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"):
headers = []
elif headers:
raise ValueError("headers for a list of dicts is not a dict or a keyword")
rows = [[row.get(k) for k in keys] for row in rows]
rows = [
row if _is_separating_line(row) else [row.get(k) for k in keys] for row in rows
]

elif (
headers == "keys"
Expand Down
107 changes: 107 additions & 0 deletions test/test_optional_inputs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Optional inputs use their public row/serialization interfaces."""

from datetime import date

import pytest

from tabulate import SEPARATING_LINE, tabulate


@pytest.fixture
def polars():
return pytest.importorskip("polars")


@pytest.mark.parametrize("headers", [(), "keys", "firstrow", ["Label", "Quantity"]])
@pytest.mark.parametrize("showindex", ["default", "always", "never", ["a", "b", "c"]])
def test_polars_rows_headers_and_index(polars, headers, showindex):
frame = polars.DataFrame({"name": ["one", "two", "three"], "quantity": [1.5, None, 3.0]})
expected_headers = frame.columns if headers == "keys" else headers
options = {"floatfmt": ".2f", "missingval": "?", "showindex": showindex, "tablefmt": "grid"}
# firstrow removes a row before an explicit index is applied.
if headers == "firstrow" and isinstance(showindex, list):
options["showindex"] = showindex[1:]
assert tabulate(frame, headers=headers, **options) == tabulate(
frame.rows(), headers=expected_headers, **options
)
assert frame.columns == ["name", "quantity"]
assert frame.shape == (3, 2)


def test_polars_empty_schema_and_dates(polars):
empty = polars.DataFrame(schema={"name": polars.String, "count": polars.Int64})
assert tabulate(empty, headers="keys") == tabulate([], headers=["name", "count"])
assert tabulate(polars.DataFrame(), headers="keys") == ""
frame = polars.DataFrame({"date": [date(2024, 1, 1)], "name": ["雪"]})
assert tabulate(frame, headers="keys") == tabulate(frame.rows(), headers=frame.columns)


@pytest.fixture(params=["pydantic", "pydantic.v1"])
def pydantic(request):
return pytest.importorskip(request.param)


def test_pydantic_serialization_and_header_mapping(pydantic):
class Row(pydantic.BaseModel):
name: str
value: float | None = None
password: str = pydantic.Field(default="private", exclude=True)

rows = [Row(name="one", value=1.25), Row(name="two")]
expected = [{"name": "one", "value": 1.25}, {"name": "two", "value": None}]
for headers in [(), "keys", "firstrow", {"name": "Label", "value": "Amount"}]:
assert tabulate(iter(rows), headers=headers, floatfmt=".1f", showindex=True) == tabulate(
expected, headers=headers, floatfmt=".1f", showindex=True
)
assert rows[0].password == "private"


def test_pydantic_nested_models_separators_and_mixed_fields(pydantic):
class Address(pydantic.BaseModel):
city: str

class User(pydantic.BaseModel):
name: str
address: Address

class Total(pydantic.BaseModel):
count: int

rows = [User(name="one", address=Address(city="Paris")), SEPARATING_LINE, Total(count=1)]
expected = [{"name": "one", "address": {"city": "Paris"}}, SEPARATING_LINE, {"count": 1}]
# The dictionary adapter needs separators left in place while discovering keys.
assert tabulate(rows, headers="keys", tablefmt="grid") == tabulate(
expected, headers="keys", tablefmt="grid"
)


def test_pydantic_v2_serializer_computed_and_root():
pydantic = pytest.importorskip("pydantic")
if not hasattr(pydantic, "RootModel"):
pytest.skip("Pydantic 2 serializer and root-model API")

class Row(pydantic.BaseModel):
amount: int

@pydantic.field_serializer("amount")
def format_amount(self, value):
return f"{value} units"

@pydantic.computed_field
@property
def double(self) -> int:
return self.amount * 2

assert tabulate([Row(amount=3)], headers="keys") == tabulate(
[{"amount": "3 units", "double": 6}], headers="keys"
)
root = pydantic.RootModel[list[int]]([1, 2])
assert tabulate([root], headers="keys") == tabulate([{"root": [1, 2]}], headers="keys")

class Scalar(pydantic.BaseModel):
@pydantic.model_serializer
def serialize(self):
return "not a row"

with pytest.raises(TypeError, match="serialize to a mapping"):
tabulate([Scalar()], headers="keys")
10 changes: 10 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ deps =
numpy
pandas
wcwidth
polars
pydantic


[testenv:py311]
Expand All @@ -67,6 +69,8 @@ deps =
numpy
pandas
wcwidth
polars
pydantic

[testenv:py312]
basepython = python3.12
Expand All @@ -83,6 +87,8 @@ deps =
numpy
pandas
wcwidth
polars
pydantic

[testenv:py313]
basepython = python3.13
Expand All @@ -99,6 +105,8 @@ deps =
numpy
pandas
wcwidth
polars
pydantic

[testenv:py314]
basepython = python3.14
Expand All @@ -115,3 +123,5 @@ deps =
numpy
pandas
wcwidth
polars
pydantic