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: apply format_mapping to None values in table formatting (#3207)

eugene777e607f46e1
diff --git a/marimo/_plugins/ui/_impl/tables/format.py b/marimo/_plugins/ui/_impl/tables/format.py
index 9de139d3c4..1d32a8c50a 100644
--- a/marimo/_plugins/ui/_impl/tables/format.py
+++ b/marimo/_plugins/ui/_impl/tables/format.py
@@ -14,16 +14,21 @@ def format_value(
# Return None if the format mapping is None
if format_mapping is None:
return value
- # Return None if the value is None
- if value is None:
- return None
- # Apply formatting logic based on column and value
+
if col in format_mapping:
formatter = format_mapping[col]
- if isinstance(formatter, str):
- return formatter.format(value)
- if callable(formatter):
- return formatter(value)
+ try:
+ if isinstance(formatter, str):
+ return formatter.format(value)
+ if callable(formatter):
+ return formatter(value)
+ except Exception as e:
+ import logging
+
+ logging.warning(
+ f"Error formatting for value {value} in column {col}: {str(e)}"
+ )
+ return value
return value
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 1e9e325627..d53443a480 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -255,6 +255,28 @@ class TestDefaultTable(unittest.TestCase):
]
assert formatted_manager == expected_data
+ def test_apply_formatting_with_none_values(self) -> None:
+ data = [
+ {"name": "Alice", "score": None, "grade": "A"},
+ {"name": "Bob", "score": 85, "grade": None},
+ {"name": "Charlie", "score": None, "grade": None},
+ ]
+ manager = DefaultTableManager(data)
+
+ format_mapping = {
+ "name": lambda x: x.upper(),
+ "score": lambda x: "No Score" if x is None else f"{x}%",
+ "grade": lambda x: "Pending" if x is None else x,
+ }
+
+ formatted_manager = manager.apply_formatting(format_mapping).data
+ expected_data = [
+ {"name": "ALICE", "score": "No Score", "grade": "A"},
+ {"name": "BOB", "score": "85%", "grade": "Pending"},
+ {"name": "CHARLIE", "score": "No Score", "grade": "Pending"},
+ ]
+ assert formatted_manager == expected_data
+
class TestColumnarDefaultTable(unittest.TestCase):
def setUp(self) -> None:
@@ -489,6 +511,28 @@ class TestColumnarDefaultTable(unittest.TestCase):
}
assert formatted_manager == expected_data
+ def test_apply_formatting_with_none_values(self) -> None:
+ data_with_none = {
+ "name": ["Alice", None, "Charlie"],
+ "age": [30, 25, None],
+ "score": [None, 85.5, 90.0],
+ }
+ manager = DefaultTableManager(data_with_none)
+
+ format_mapping = {
+ "name": lambda x: "UNKNOWN" if x is None else x.upper(),
+ "age": lambda x: "N/A" if x is None else f"Age: {x}",
+ "score": lambda x: "Missing" if x is None else f"{x:.1f}%",
+ }
+
+ formatted_manager = manager.apply_formatting(format_mapping).data
+ expected_data = {
+ "name": ["ALICE", "UNKNOWN", "CHARLIE"],
+ "age": ["Age: 30", "Age: 25", "N/A"],
+ "score": ["Missing", "85.5%", "90.0%"],
+ }
+ assert formatted_manager == expected_data
+
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
)
@@ -593,6 +637,40 @@ class TestDictionaryDefaultTable(unittest.TestCase):
)
assert formatted_manager.data == self.manager.data
+ def test_apply_formatting_with_none_values(self) -> None:
+ manager = DefaultTableManager(
+ {
+ "a": None,
+ "b": 2,
+ "c": None,
+ }
+ )
+
+ # Test raw dictionary formatting
+ assert manager.apply_formatting(
+ {"value": lambda x: "N/A" if x is None else x * 2}
+ ).data == {
+ "a": None,
+ "b": 2,
+ "c": None,
+ }
+
+ # Test converted to rows formatting
+ formatted_data = (
+ DefaultTableManager(manager.to_data())
+ .apply_formatting(
+ {"value": lambda x: "N/A" if x is None else x * 2}
+ )
+ .data
+ )
+
+ expected_data = [
+ {"key": "a", "value": "N/A"},
+ {"key": "b", "value": 4},
+ {"key": "c", "value": "N/A"},
+ ]
+ assert formatted_data == expected_data
+
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
)
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 23f0d88642..c987ae741d 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -648,6 +648,50 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
)
assert_frame_equal(formatted_data, expected_data)
+ def test_apply_formatting_with_none_values(self) -> None:
+ import polars as pl
+
+ # Create test data with None values in different types of columns
+ data = pl.DataFrame(
+ {
+ "strings": ["a", None, "c"],
+ "integers": [1, None, 3],
+ "floats": [1.5, None, 3.5],
+ "booleans": [True, None, False],
+ "dates": [
+ datetime.date(2021, 1, 1),
+ None,
+ datetime.date(2021, 1, 3),
+ ],
+ "lists": [[1, 2], None, [5, 6]],
+ }
+ )
+ manager = NarwhalsTableManager.from_dataframe(data)
+
+ format_mapping: FormatMapping = {
+ "strings": lambda x: "MISSING" if x is None else x.upper(),
+ "integers": lambda x: -100 if x is None else x * 2,
+ "floats": lambda x: "---" if x is None else f"{x:.1f}",
+ "booleans": lambda x: "MISSING" if x is None else str(x).upper(),
+ "dates": lambda x: "No Date"
+ if x is None
+ else x.strftime("%Y-%m-%d"),
+ "lists": lambda x: "Empty" if x is None else f"List({len(x)})",
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping).data
+ expected_data = pl.DataFrame(
+ {
+ "strings": ["A", "MISSING", "C"],
+ "integers": [2, -100, 6],
+ "floats": ["1.5", "---", "3.5"],
+ "booleans": ["TRUE", "MISSING", "FALSE"],
+ "dates": ["2021-01-01", "No Date", "2021-01-03"],
+ "lists": ["List(2)", "Empty", "List(2)"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 8d070c79f2..431cd88936 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -629,7 +629,7 @@ class TestPandasTableManager(unittest.TestCase):
[4, 5, 6],
[7, 8, 9],
], # No formatting applied
- "G": [None, "text", "3.14"],
+ "G": ["None", "text", "3.14"],
}
)
assert_frame_equal(formatted_data, expected_data)
@@ -753,12 +753,38 @@ class TestPandasTableManager(unittest.TestCase):
[4, 5, 6],
[7, 8, 9],
], # No formatting applied
- "G": [None, "text", "3.14"],
+ "G": ["None", "text", "3.14"],
"H": [2.23606797749979, 5.0, 7.810249675906654],
}
)
assert_frame_equal(formatted_data, expected_data)
+ def test_apply_formatting_with_none_values(self) -> None:
+ data = pd.DataFrame(
+ {
+ "A": [1, None, 3],
+ "B": [None, "text", None],
+ "C": [1.0, 2.0, None],
+ }
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "A": lambda x: "N/A" if pd.isna(x) else x * 2,
+ "B": lambda x: "Missing" if pd.isna(x) else x.upper(),
+ "C": lambda x: "---" if pd.isna(x) else f"{x:.2f}",
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping).data
+ expected_data = pd.DataFrame(
+ {
+ "A": [2, "N/A", 6],
+ "B": ["Missing", "TEXT", "Missing"],
+ "C": ["1.00", "2.00", "---"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
def test_empty_dataframe(self) -> None:
empty_df = pd.DataFrame()
empty_manager = self.factory.create()(empty_df)
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 1de1c4a5d8..7823351f22 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -676,6 +676,50 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
)
assert_frame_equal(formatted_data, expected_data)
+ def test_apply_formatting_with_none_values(self) -> None:
+ import polars as pl
+
+ # Create test data with None values in different types of columns
+ data = pl.DataFrame(
+ {
+ "strings": ["a", None, "c"],
+ "integers": [1, None, 3],
+ "floats": [1.5, None, 3.5],
+ "booleans": [True, None, False],
+ "dates": [
+ datetime.date(2021, 1, 1),
+ None,
+ datetime.date(2021, 1, 3),
+ ],
+ "lists": [[1, 2], None, [5, 6]],
+ },
+ )
+ manager = self.factory.create()(data)
+
+ format_mapping: FormatMapping = {
+ "strings": lambda x: "MISSING" if x is None else x.upper(),
+ "integers": lambda x: -100 if x is None else x * 2,
+ "floats": lambda x: "---" if x is None else f"{x:.1f}",
+ "booleans": lambda x: "MISSING" if x is None else str(x).upper(),
+ "dates": lambda x: "No Date"
+ if x is None
+ else x.strftime("%Y-%m-%d"),
+ "lists": lambda x: "Empty" if x is None else f"List({len(x)})",
+ }
+
+ formatted_data = manager.apply_formatting(format_mapping).data
+ expected_data = pl.DataFrame(
+ {
+ "strings": ["A", "MISSING", "C"],
+ "integers": [2, -100, 6],
+ "floats": ["1.5", "---", "3.5"],
+ "booleans": ["TRUE", "MISSING", "FALSE"],
+ "dates": ["2021-01-01", "No Date", "2021-01-03"],
+ "lists": ["List(2)", "Empty", "List(2)"],
+ }
+ )
+ assert_frame_equal(formatted_data, expected_data)
+
def test_empty_dataframe(self) -> None:
import polars as pl
diff --git a/tests/_plugins/ui/_impl/tables/test_table_utils.py b/tests/_plugins/ui/_impl/tables/test_table_utils.py
index 4b39d172e5..410831f35d 100644
--- a/tests/_plugins/ui/_impl/tables/test_table_utils.py
+++ b/tests/_plugins/ui/_impl/tables/test_table_utils.py
@@ -36,6 +36,10 @@ def test_format_value():
format_mapping = {"col1": lambda x: f"{x:.2f} units"}
assert format_value("col1", 123.456, format_mapping) == "123.46 units"
+ # Test with None formatter
+ format_mapping = {"col1": lambda x: "None value" if x is None else x}
+ assert format_value("col1", None, format_mapping) == "None value"
+
def test_format_row():
# Test with string formatter
@@ -77,6 +81,15 @@ def test_format_row():
expected = {"col1": None, "col2": "78.9"}
assert format_row(row, format_mapping) == expected
+ # Test with None formatter
+ format_mapping = {
+ "col1": lambda x: "None value" if x is None else x,
+ "col2": lambda x: "N/A" if x is None else x,
+ }
+ row = {"col1": None, "col2": None}
+ expected = {"col1": "None value", "col2": "N/A"}
+ assert format_row(row, format_mapping) == expected
+
def test_format_column():
# Test with string formatter
@@ -114,3 +127,9 @@ def test_format_column():
values = []
expected = []
assert format_column("col1", values, format_mapping) == expected
+
+ # Test with None formatter
+ format_mapping = {"col1": lambda x: "Missing" if x is None else x}
+ values = [123.456, None, 78.9]
+ expected = [123.456, "Missing", 78.9]
+ assert format_column("col1", values, format_mapping) == expected