Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix(tables): preserve columns in DefaultTableManager exports (#9258)

Kiran Gadhave0381288cc496
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 91c957a901..6a90b96df3 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import functools
from collections import defaultdict
from collections.abc import Sequence
+from itertools import zip_longest
from typing import TYPE_CHECKING, Any, cast
from marimo._data.models import BinValue, ColumnStats, ExternalDataType
@@ -46,6 +47,7 @@ JsonTableData = (
# For non-column-oriented data, we use "key" and "value" as the column names
KEY = "key"
VALUE = "value"
+MAX_ROWS_TO_SCAN = 1000 # only scan first 1000 rows to infer column names
class DefaultTableManager(TableManager[JsonTableData]):
@@ -154,7 +156,7 @@ class DefaultTableManager(TableManager[JsonTableData]):
# Row major data
return DefaultTableManager(
[
- {key: row[key] for key in columns}
+ {key: row.get(key) for key in columns}
for row in self._normalize_data(self.data)
]
)
@@ -351,8 +353,11 @@ class DefaultTableManager(TableManager[JsonTableData]):
del force
if isinstance(self.data, dict):
if self.is_column_oriented:
- first = next(iter(self.data.values()), None)
- return len(cast(list[Any], first))
+ # iterate on all columns to find longest
+ return max(
+ (len(cast(list[Any], v)) for v in self.data.values()),
+ default=0,
+ )
else:
return len(self.data)
return len(self.data)
@@ -363,10 +368,21 @@ class DefaultTableManager(TableManager[JsonTableData]):
def get_column_names(self) -> list[str]:
if isinstance(self.data, dict):
if not self.is_column_oriented:
+ # i.e. the dict is a mapping of key-value pairs, not column-oriented data
return [KEY, VALUE]
return list(self.data.keys())
- first = next(iter(self.data), None)
- return list(first.keys()) if isinstance(first, dict) else ["value"]
+
+ if not self.data or not isinstance(self.data[0], dict):
+ return ["value"]
+
+ seen: dict[str, None] = {}
+ # iterate on first 1000 rows to find column names
+ for row in self.data[:MAX_ROWS_TO_SCAN]:
+ if isinstance(row, dict):
+ for key in row:
+ seen.setdefault(key)
+
+ return list(seen)
def get_unique_column_values(self, column: str) -> list[str | int | float]:
return sorted(
@@ -471,7 +487,10 @@ class DefaultTableManager(TableManager[JsonTableData]):
column_names = list(data.keys())
return [
dict(zip(column_names, row_values, strict=False))
- for row_values in zip(*column_values, strict=False)
+ for row_values in zip_longest(
+ *column_values, # type: ignore[arg-type]
+ fillvalue=None, # fills shorter rows with None
+ )
]
# If its a dictionary, convert to key-value pairs
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 9b6a04d009..be6795c96d 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -1181,6 +1181,63 @@ class TestDefaultTableWithComplexData(unittest.TestCase):
)
+class TestHeterogeneousRowData(unittest.TestCase):
+ """Row-oriented data where rows have differing key sets."""
+
+ def test_get_column_names_unions_keys(self) -> None:
+ mgr = DefaultTableManager([{"a": 1}, {"a": 2, "b": 3}])
+ assert mgr.get_column_names() == ["a", "b"]
+
+ def test_get_column_names_disjoint_keys(self) -> None:
+ mgr = DefaultTableManager([{"a": 1}, {"b": 2}])
+ assert mgr.get_column_names() == ["a", "b"]
+
+ def test_get_column_names_preserves_first_seen_order(self) -> None:
+ mgr = DefaultTableManager([{"b": 1}, {"a": 2, "b": 3}])
+ assert mgr.get_column_names() == ["b", "a"]
+
+ def test_get_column_names_empty_dict_rows(self) -> None:
+ assert DefaultTableManager([{}, {}]).get_column_names() == []
+
+ def test_to_csv_str_includes_all_columns(self) -> None:
+ mgr = DefaultTableManager([{"a": 1}, {"a": 2, "b": 3}])
+ assert mgr.to_csv_str() == "a,b\n1,\n2,3\n"
+
+ def test_to_json_str_preserves_per_row_keys(self) -> None:
+ mgr = DefaultTableManager([{"a": 1}, {"a": 2, "b": 3}])
+ assert json.loads(mgr.to_json_str()) == [
+ {"a": 1},
+ {"a": 2, "b": 3},
+ ]
+
+ def test_select_columns_fills_missing_keys_with_none(self) -> None:
+ mgr = DefaultTableManager([{"a": 1}, {"a": 2, "b": 3}])
+ assert mgr.select_columns(["a", "b"]).data == [
+ {"a": 1, "b": None},
+ {"a": 2, "b": 3},
+ ]
+
+
+class TestMismatchedColumnLengths(unittest.TestCase):
+ """Column-oriented data where columns have differing lengths."""
+
+ def test_get_num_rows_is_max_column_length(self) -> None:
+ mgr = DefaultTableManager({"a": [1, 2, 3], "b": [4, 5]})
+ assert mgr.get_num_rows() == 3
+
+ def test_to_csv_str_pads_short_columns(self) -> None:
+ mgr = DefaultTableManager({"a": [1, 2, 3], "b": [4, 5]})
+ assert mgr.to_csv_str() == "a,b\n1,4\n2,5\n3,\n"
+
+ def test_to_json_str_pads_short_columns_with_null(self) -> None:
+ mgr = DefaultTableManager({"a": [1, 2, 3], "b": [4, 5]})
+ assert json.loads(mgr.to_json_str()) == [
+ {"a": 1, "b": 4},
+ {"a": 2, "b": 5},
+ {"a": 3, "b": None},
+ ]
+
+
def test_validate_header_tooltip_valid() -> None:
columns = {"name", "age", "birth_year"}
mapping = {"name": "Name of person", "age": "Age in years"}