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: altair's code gen with comment (#5767)

Shahmir Varqha7fa7808aca4a
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.py
index 1c300a1176..50cf574f60 100644
--- a/marimo/_data/charts.py
+++ b/marimo/_data/charts.py
@@ -17,6 +17,8 @@ from marimo._utils.theme import get_current_theme
if TYPE_CHECKING:
import altair as alt
+REPLACE_DF_COMMENT = "# <-- replace with data"
+
@abc.abstractmethod
class ChartBuilder:
@@ -37,6 +39,20 @@ class ChartBuilder:
"""If simple, return simple altair code."""
raise NotImplementedError
+ def altair_code_with_comment(
+ self, data: str, column: str, simple: bool
+ ) -> str:
+ """
+ Return the altair code with a comment to replace the df and produces an empty chart.
+ This is useful when we don't know the var name of the data.
+ """
+ code = self.altair_code(data, column, simple)
+ code = code.replace(
+ f"alt.Chart({data})",
+ f"alt.Chart([]) {REPLACE_DF_COMMENT}",
+ )
+ return code
+
@dataclass
class ChartParams:
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index 5b2065f054..e9bff8f05f 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -258,7 +258,9 @@ def _get_altair_chart(
should_limit_to_10_items = True
chart_builder = get_chart_builder(column_type, should_limit_to_10_items)
- code = chart_builder.altair_code(table_name, column_name, simple=True)
+ code = chart_builder.altair_code_with_comment(
+ table_name, column_name, simple=True
+ )
# Filter the data to the column we want
column_data = table.select_columns([column_name]).data
diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.py
index 12436f3a69..b1e19a3411 100644
--- a/tests/_data/test_charts.py
+++ b/tests/_data/test_charts.py
@@ -7,6 +7,7 @@ from typing import Any
import pytest
from marimo._data.charts import (
+ REPLACE_DF_COMMENT,
ChartBuilder,
DateChartBuilder,
get_chart_builder,
@@ -89,6 +90,12 @@ def test_charts_bad_characters():
snapshot("charts_bad_characters.txt", "\n\n".join(outputs))
+def test_charts_altair_code_with_comment():
+ builder = get_chart_builder("string", False)
+ code = builder.altair_code_with_comment("df", "some_column", simple=True)
+ assert f"alt.Chart([]) {REPLACE_DF_COMMENT}" in code
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_charts_altair_json():
outputs: list[str] = []