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
chore: use narhwals to scalar (#2721)
Myles Scolnick9eb1f37567f1
diff --git a/marimo/_data/series.py b/marimo/_data/series.pyindex 2cc2e942dc..4ba0ae161d 100644--- a/marimo/_data/series.py+++ b/marimo/_data/series.py@@ -7,7 +7,10 @@ from typing import Any, castimport narwhals.stable.v1 as nw-from marimo._utils.narwhals_utils import assert_narwhals_series+from marimo._utils.narwhals_utils import (+ assert_narwhals_series,+ unwrap_py_scalar,+)# TODO: use series type when released# https://github.com/narwhals-dev/narwhals/pull/991@@ -60,8 +63,7 @@ def get_number_series_info(series: nw.Series) -> NumberSeriesInfo:assert_narwhals_series(series)def validate_number(value: Any) -> float:- if hasattr(value, "as_py"):- return validate_number(value.as_py())+ value = unwrap_py_scalar(value)value = float(value)if not isinstance(value, (int, float)):raise ValueError("Expected a number. Got: " + str(type(value)))@@ -95,12 +97,11 @@ def get_date_series_info(series: nw.Series) -> DateSeriesInfo:assert_narwhals_series(series)def validate_date(value: Any) -> str:+ value = unwrap_py_scalar(value)if isinstance(value, datetime.date):return value.strftime("%Y-%m-%d")if hasattr(value, "strftime"):return cast(str, value.strftime("%Y-%m-%d"))- if hasattr(value, "as_py"):- return validate_date(value.as_py())raise ValueError("Expected a date. Got: " + str(type(value)))return DateSeriesInfo(@@ -118,6 +119,7 @@ def get_datetime_series_info(series: nw.Series) -> DateSeriesInfo:assert_narwhals_series(series)def validate_datetime(value: Any) -> str:+ value = unwrap_py_scalar(value)if isinstance(value, datetime.datetime):return value.strftime("%Y-%m-%dT%H:%M:%S")if isinstance(value, datetime.date):@@ -126,8 +128,6 @@ def get_datetime_series_info(series: nw.Series) -> DateSeriesInfo:return value.strftime("%Y-%m-%d")if hasattr(value, "strftime"):return cast(str, value.strftime("%Y-%m-%d"))- if hasattr(value, "as_py"):- return validate_datetime(value.as_py())raise ValueError("Expected a datetime. Got: " + str(type(value)))return DateSeriesInfo(diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex c476c711bb..5906f5388f 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -22,6 +22,7 @@ from marimo._utils.narwhals_utils import (is_narwhals_integer_type,is_narwhals_string_type,is_narwhals_temporal_type,+ unwrap_py_scalar,)@@ -132,8 +133,7 @@ class NarwhalsTableManager(query = query.lower()expressions: list[Any] = []- for column in self.data.columns:- dtype = self.data[column].dtype+ for column, dtype in self.data.schema.items():if dtype == nw.String:expressions.append(nw.col(column).str.contains(query))elif dtype == nw.List(nw.String):@@ -164,12 +164,12 @@ class NarwhalsTableManager(summary = self._get_summary_internal(column)for key, value in summary.__dict__.items():if value is not None:- summary.__dict__[key] = _maybe_convert_as_py(value)+ summary.__dict__[key] = unwrap_py_scalar(value)return summarydef _get_summary_internal(self, column: str) -> ColumnSummary:# If column is not in the dataframe, return an empty summary- if column not in self.data.columns:+ if column not in self.data.schema:return ColumnSummary()col = self.data[column]total = len(col)@@ -251,13 +251,17 @@ class NarwhalsTableManager(return None# Otherwise, we can get the number of rows from the shape- return self.data.shape[0]+ try:+ return self.data.shape[0]+ except Exception:+ # narwhals will raise on metadata-only frames+ return Nonedef get_num_columns(self) -> int:- return len(self.data.columns)+ return len(self.data.schema.names())def get_column_names(self) -> list[str]:- return self.data.columns+ return self.data.schema.names()def get_unique_column_values(self, column: str) -> list[str | int | float]:return self.data[column].unique().to_list()@@ -281,13 +285,3 @@ class NarwhalsTableManager(if rows is None:return f"{df_type}: {columns:,} columns"return f"{df_type}: {rows:,} rows x {columns:,} columns"---# pyarrow use wrapper types for primitives-# so we need to convert to the primitive type-def _maybe_convert_as_py(value: Any) -> Any:- if hasattr(value, "to_pylist"):- return value.to_pylist()- if hasattr(value, "as_py"):- return value.as_py()- return valuediff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex 86560234de..d706cd1589 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.rich_help import mddoc-from marimo._plugins.ui._impl import tablefrom marimo._runtime.context.types import (ContextNotInitializedError,get_context,@@ -90,6 +89,8 @@ def sql()if output:+ from marimo._plugins.ui._impl import table+t = table.table(df,selection=None,diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.pyindex 327d93dd66..0d384f92c0 100644--- a/marimo/_utils/narwhals_utils.py+++ b/marimo/_utils/narwhals_utils.py@@ -131,3 +131,14 @@ def unwrap_narwhals_dataframe(df: Any) -> Any:if isinstance(df, nw.DataFrame):return df.to_native() # type: ignore[return-value]return df+++def unwrap_py_scalar(value: Any) -> Any:+ """+ Convert a narwhals value to a python scalar if possible, otherwise return+ the value as is.+ """+ try:+ return nw.to_py_scalar(value)+ except ValueError:+ return valuediff --git a/tests/_data/mocks.py b/tests/_data/mocks.pyindex 02c707cfff..ea8739a368 100644--- a/tests/_data/mocks.py+++ b/tests/_data/mocks.py@@ -8,7 +8,7 @@ from marimo._dependencies.dependencies import DependencyManagerif TYPE_CHECKING:from narwhals.typing import IntoDataFrame-DFType = Literal["pandas", "polars", "ibis", "pyarrow"]+DFType = Literal["pandas", "polars", "ibis", "pyarrow", "duckdb"]def create_dataframes(@@ -52,16 +52,28 @@ def create_dataframes(dfs.append(pa.Table.from_pydict(data))+ if DependencyManager.duckdb.has() and should_include("duckdb"):+ import duckdb++ if DependencyManager.polars.has():+ import polars as pl++ duck_df = pl.DataFrame(data)+ relation = duckdb.sql("SELECT * FROM duck_df")+ del duck_df+ dfs.append(relation)+return dfsdef create_series(data: list[Any]) -> list[Any]:+ series: list[Any] = []if DependencyManager.pandas.has():import pandas as pd- return [pd.Series(data)]+ series.append(pd.Series(data))if DependencyManager.polars.has():import polars as pl- return [pl.Series(data)]- return []+ series.append(pl.Series(data))+ return seriesdiff --git a/tests/_data/test_get_datasets.py b/tests/_data/test_get_datasets.pyindex 7bff1c02e5..6608db76fe 100644--- a/tests/_data/test_get_datasets.py+++ b/tests/_data/test_get_datasets.py@@ -1,13 +1,17 @@from __future__ import annotations+from typing import Any+import pytestfrom marimo._data.get_datasets import (get_datasets_from_duckdb,+ get_datasets_from_variables,has_updates_to_datasource,)from marimo._data.models import DataTable, DataTableColumnfrom marimo._dependencies.dependencies import DependencyManager+from tests._data.mocks import create_dataframesHAS_DEPS = DependencyManager.duckdb.has()@@ -144,3 +148,40 @@ def test_get_datasets() -> None:],)]+++ "df",+ create_dataframes({"A": [1, 2, 3], "B": ["a", "a", "a"]}),+)+def test_get_datasets_from_variables(df: Any) -> None:+ datatests = get_datasets_from_variables([("my_df", df), ("non_df", 123)])+ # We don't compare these values+ external_type1 = datatests[0].columns[0].external_type+ external_type2 = datatests[0].columns[1].external_type++ rows = datatests[0].num_rows+ assert rows is None or rows == 3++ assert datatests == [+ DataTable(+ name="my_df",+ source_type="local",+ source="memory",+ num_rows=rows,+ num_columns=2,+ variable_name="my_df",+ columns=[+ DataTableColumn(+ name="A",+ type="integer",+ external_type=external_type1,+ ),+ DataTableColumn(+ name="B",+ type="string",+ external_type=external_type2,+ ),+ ],+ )+ ]diff --git a/tests/_data/test_series.py b/tests/_data/test_series.pyindex 22b45ae961..9597c6bffa 100644--- a/tests/_data/test_series.py+++ b/tests/_data/test_series.py@@ -27,7 +27,7 @@ HAS_DEPS = (@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 2, 3], "B": ["a", "a", "a"]}, exclude=["ibis"]+ {"A": [1, 2, 3], "B": ["a", "a", "a"]}, exclude=["ibis", "duckdb"]),)def test_number_series(@@ -49,7 +49,6 @@ def test_number_series(create_series([1, 2, 3]),)def test_get_with_no_name(series: Any) -> None:- series.name = Noneassert get_number_series_info(series).label == ""@@ -57,7 +56,7 @@ def test_get_with_no_name(series: Any) -> None:@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 2, 3], "B": ["a", "b", "b"]}, exclude=["ibis"]+ {"A": [1, 2, 3], "B": ["a", "b", "b"]}, exclude=["ibis", "duckdb"]),)def test_categorical_series(df: Any) -> None:@@ -84,7 +83,7 @@ def test_categorical_series(df: Any) -> None:datetime(2024, 1, 3),],},- exclude=["ibis"],+ exclude=["ibis", "duckdb"],),)def test_date_series(df: Any) -> None:@@ -113,7 +112,7 @@ def test_date_series(df: Any) -> None:datetime(2024, 1, 3, 15, 45),],},- exclude=["ibis"],+ exclude=["ibis", "duckdb"],),)def test_datetime_series(df: Any) -> None:@@ -142,17 +141,17 @@ def test_datetime_series(df: Any) -> None:datetime(2024, 1, 3, 15, 45),],},- include=["ibis"],+ include=["ibis", "duckdb"],),)def test_ibis_fails(df: Any) -> None:- with pytest.raises(ValueError):+ with pytest.raises((TypeError, ValueError)):get_number_series_info(df["A"])- with pytest.raises(ValueError):+ with pytest.raises((TypeError, ValueError)):get_category_series_info(df["B"])- with pytest.raises(ValueError):+ with pytest.raises((TypeError, ValueError)):get_date_series_info(df["C"])- with pytest.raises(ValueError):+ with pytest.raises((TypeError, ValueError)):get_datetime_series_info(df["C"])diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.pyindex dd2e260346..a78246260d 100644--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py@@ -29,7 +29,9 @@ if TYPE_CHECKING:@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),+ create_dataframes(+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["duckdb"]+ ),)def test_to_marimo_json(df: IntoDataFrame):result = _to_marimo_json(df)@@ -43,7 +45,9 @@ def test_to_marimo_json(df: IntoDataFrame):@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),+ create_dataframes(+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["duckdb"]+ ),)def test_to_marimo_csv(df: IntoDataFrame):result = _to_marimo_csv(df)@@ -57,7 +61,9 @@ def test_to_marimo_csv(df: IntoDataFrame):@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),+ create_dataframes(+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["duckdb"]+ ),)def test_to_marimo_inline_csv(df: IntoDataFrame):result = _to_marimo_inline_csv(df)@@ -72,7 +78,9 @@ def test_to_marimo_inline_csv(df: IntoDataFrame):@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes({"A": [1, 2, 3], "B": ["a", "b", "c"]}),+ create_dataframes(+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["duckdb"]+ ),)def test_data_to_json_string(df: IntoDataFrame):result = _data_to_json_string(df)@@ -88,7 +96,7 @@ def test_data_to_json_string(df: IntoDataFrame):"df",# We skip pyarrow because it's csv is formatted differentlycreate_dataframes(- {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["pyarrow"]+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["pyarrow", "duckdb"]),)def test_data_to_csv_string(df: IntoDataFrame):@@ -103,7 +111,7 @@ def test_data_to_csv_string(df: IntoDataFrame):@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes({}, exclude=["ibis"]),+ create_dataframes({}, exclude=["ibis", "duckdb"]),)def test_to_marimo_json_empty_dataframe(df: IntoDataFrame):result = _to_marimo_json(df)@@ -119,7 +127,8 @@ def test_to_marimo_json_empty_dataframe(df: IntoDataFrame):@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 1, 3], "B": ["a", None, "c"], "C": [True, False, None]}+ {"A": [1, 1, 3], "B": ["a", None, "c"], "C": [True, False, None]},+ exclude=["duckdb"],),)def test_to_marimo_csv_with_missing_values(df: IntoDataFrame):@@ -137,7 +146,7 @@ def test_to_marimo_csv_with_missing_values(df: IntoDataFrame):"df",create_dataframes({"A": range(10000), "B": [f"value_{i}" for i in range(10000)]},- exclude=["pyarrow"],+ exclude=["pyarrow", "duckdb"],),)def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):@@ -166,7 +175,8 @@ def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):"df",# We skip pyarrow because it's json is missing new linescreate_dataframes(- {"A": [1, 2, 3], "B": ['a"b', "c,d", "e\nf"]}, exclude=["pyarrow"]+ {"A": [1, 2, 3], "B": ['a"b', "c,d", "e\nf"]},+ exclude=["pyarrow", "duckdb"],),)def test_data_to_json_string_with_special_characters(@@ -197,7 +207,7 @@ def test_data_to_json_string_with_special_characters(],"category": ["a", "b", "c"],},- exclude=["ibis"],+ exclude=["ibis", "duckdb"],),)def test_data_to_csv_string_with_different_dtypes(df: IntoDataFrame):diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.pyindex f1a986aec1..2a38b0f5cb 100644--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py@@ -50,7 +50,8 @@ class TestDataframes:@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 2, 3], "B": ["a", "a", "a"]}, exclude=["pyarrow"]+ {"A": [1, 2, 3], "B": ["a", "a", "a"]},+ exclude=["pyarrow", "duckdb"],),)def test_dataframe(@@ -124,7 +125,8 @@ class TestDataframes:@pytest.mark.parametrize("df",create_dataframes(- {"1": [1, 2, 3], "2": ["a", "a", "a"]}, exclude=["pyarrow"]+ {"1": [1, 2, 3], "2": ["a", "a", "a"]},+ exclude=["pyarrow", "duckdb"],),)def test_dataframe_page_size(@@ -161,17 +163,17 @@ class TestDataframes:"df",[*create_dataframes(- {"A": [], "B": []}, exclude=["pyarrow"]+ {"A": [], "B": []}, exclude=["pyarrow", "duckdb"]), # Empty DataFrame*create_dataframes(- {"A": [1], "B": ["a"]}, exclude=["pyarrow"]+ {"A": [1], "B": ["a"]}, exclude=["pyarrow", "duckdb"]), # Single row DataFrame*create_dataframes({"A": range(1, 1001),"B": [f"value_{i}" for i in range(1, 1001)],},- exclude=["pyarrow"],+ exclude=["pyarrow", "duckdb"],), # Large DataFrame],)@@ -200,7 +202,7 @@ class TestDataframes:@pytest.mark.parametrize("df",create_dataframes(- {"A": range(100), "B": ["a"] * 100}, exclude=["pyarrow"]+ {"A": range(100), "B": ["a"] * 100}, exclude=["pyarrow", "duckdb"]),)def test_dataframe_with_custom_page_size(df: Any) -> None:@@ -239,7 +241,8 @@ class TestDataframes:@pytest.mark.parametrize("df",create_dataframes(- {"A": range(1000), "B": ["a"] * 1000}, exclude=["pyarrow"]+ {"A": range(1000), "B": ["a"] * 1000},+ exclude=["pyarrow", "duckdb"],),)def test_dataframe_with_limit(df: Any) -> None:@@ -257,7 +260,8 @@ class TestDataframes:@pytest.mark.parametrize("df",create_dataframes(- {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=["pyarrow"]+ {"A": [1, 2, 3], "B": ["a", "b", "c"]},+ exclude=["pyarrow", "duckdb"],),)def test_dataframe_error_handling(df: Any) -> None:diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex dd4e4df9a0..e75400c322 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -56,7 +56,7 @@ class TestAltairChart:"field_2": [1, 2, 3, 4],"field_3": [10, 20, 30, 40],},- exclude=["ibis"],+ exclude=["ibis", "duckdb"],),)def test_filter_dataframe(df: ChartDataType) -> None:@@ -121,7 +121,7 @@ class TestAltairChart:datetime.datetime(2020, 1, 10),],},- exclude=["ibis"],+ exclude=["ibis", "duckdb"],),)def test_filter_dataframe_with_dates(@@ -471,7 +471,7 @@ def test_chart_with_binning(df: IntoDataFrame):"y": [1, 2, 3, 4],"category": ["A", "A", "B", "B"],},- exclude=["ibis", "pyarrow"],+ exclude=["ibis", "pyarrow", "duckdb"],),)def test_apply_selection(df: IntoDataFrame):diff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.pyindex 9a20a6866b..d207fa8e07 100644--- a/tests/_utils/test_narwhals_utils.py+++ b/tests/_utils/test_narwhals_utils.py@@ -23,7 +23,7 @@ if TYPE_CHECKING:@pytest.mark.parametrize("df",create_dataframes(- {"a": [1, 2, 3], "b": ["x", "y", "z"]}, exclude=["ibis"]+ {"a": [1, 2, 3], "b": ["x", "y", "z"]}, exclude=["ibis", "duckdb"]),)@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")