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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: date serialization in altair without timezones (#4286)
Myles Scolnicke36a773ae75f
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.pyindex 4fb8e02645..11ec04d646 100644--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py@@ -9,12 +9,12 @@ from narwhals.typing import IntoDataFrameimport marimo._output.data.data as mo_datafrom marimo import _loggers-from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.tables.utils import (get_table_manager,get_table_manager_or_none,)from marimo._utils.data_uri import build_data_url+from marimo._utils.narwhals_utils import can_narwhalifyLOGGER = _loggers.marimo_logger()@@ -66,6 +66,7 @@ def _to_marimo_arrow(data: Data, **kwargs: Any) -> _TransformResult:Convert data to arrow format, falls back to CSV if not possible."""del kwargs+ data = _maybe_sanitize_dataframe(data)try:data_arrow = get_table_manager(data).to_arrow_ipc()except NotImplementedError:@@ -96,28 +97,7 @@ def _to_marimo_inline_csv(data: Data, **kwargs: Any) -> _TransformResult:# Copied from https://github.com/altair-viz/altair/blob/0ca83784e2455f2b84d0f6d789af2abbe8814348/altair/utils/data.py#L263C1-L288C10def _data_to_json_string(data: _DataType) -> str:"""Return a JSON string representation of the input data"""- import altair as alt- import pandas as pd-- if isinstance(data, pd.DataFrame):- if "sanitize_pandas_dataframe" in dir(alt.utils):- sanitized = alt.utils.sanitize_pandas_dataframe(data) # type: ignore[attr-defined]- elif "sanitize_dataframe" in dir(alt.utils):- sanitized = alt.utils.sanitize_dataframe(data) # type: ignore[attr-defined]- else:- raise NotImplementedError(- "No sanitize_pandas_dataframe or "- "sanitize_dataframe in altair.utils."- )- as_str = sanitized.to_json(orient="records", double_precision=15)- assert isinstance(as_str, str)- return as_str-- if DependencyManager.narwhals.has():- import narwhals-- if isinstance(data, narwhals.DataFrame):- return _data_to_json_string(narwhals.to_native(data))+ data = _maybe_sanitize_dataframe(data)tm = get_table_manager_or_none(data)if tm:@@ -131,9 +111,31 @@ def _data_to_json_string(data: _DataType) -> str:def _data_to_csv_string(data: _DataType) -> str:"""Return a CSV string representation of the input data"""+ data = _maybe_sanitize_dataframe(data)+return get_table_manager(data).to_csv().decode("utf-8")+def _maybe_sanitize_dataframe(data: Any) -> Any:+ """Sanitize a pandas or narwhals DataFrame for JSON serialization"""+ import altair as alt++ if can_narwhalify(data) and "sanitize_narwhals_dataframe" in dir(+ alt.utils+ ):+ narwhals_data = nw.from_native(data)+ try:+ res: nw.DataFrame[Any] = alt.utils.sanitize_narwhals_dataframe(+ narwhals_data # type: ignore[arg-type]+ )+ return res.to_native() # type: ignore[return-value]+ except Exception as e:+ LOGGER.warning(f"Failed to sanitize narwhals dataframe: {e}")+ return data++ return data++def register_transformers() -> None:"""Register custom data transformers for Altair.diff --git a/marimo/_smoke_tests/altair/chart_dates.py b/marimo/_smoke_tests/altair/chart_dates.pynew file mode 100644index 0000000000..1a08909de7--- /dev/null+++ b/marimo/_smoke_tests/altair/chart_dates.py@@ -0,0 +1,55 @@+import marimo++__generated_with = "0.11.30"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)+++def _():+ import polars as pl+ import altair as alt+ from datetime import date+ return alt, date, pl+++def _(date, pl):+ df = pl.DataFrame({"x": [date(2025, 1, 1)], "y": [1.0]})+ return (df,)+++def _(alt, df):+ chart = alt.Chart(df).mark_bar().encode(x="x:T", y="y:Q")+ chart+ return (chart,)+++def _(chart, mo):+ mo.ui.altair_chart(chart)+ return+++def _(alt, chart, mo):+ with alt.data_transformers.enable("marimo_csv"):+ mo.output.append(chart)+ return+++def _(alt, chart, mo):+ with alt.data_transformers.enable("marimo_json"):+ mo.output.append(chart)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.pyindex 6a4b046580..e93169f5a9 100644--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py@@ -18,7 +18,6 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (_to_marimo_json,register_transformers,)-from marimo._utils.narwhals_utils import dataframe_to_csvfrom tests._data.mocks import create_dataframesHAS_DEPS = DependencyManager.pandas.has() and DependencyManager.altair.has()@@ -214,9 +213,6 @@ def test_data_to_json_string_with_special_characters(def test_data_to_csv_string_with_different_dtypes(df: IntoDataFrame):result = _data_to_csv_string(df)assert isinstance(result, str)- # NB: These can differ based on datetime canonicalization --- our table- # manager always includes H:M:S:.f for pandas, but narwhals doesn't.- assert result == dataframe_to_csv(df)@patch("altair.data_transformers")