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
improvement: narwhals perf and arg name changes (#4994)
Myles Scolnick568bdfabd0f4
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.pyindex 08b3df1caa..ebab61d3f1 100644--- a/marimo/_output/data/data.py+++ b/marimo/_output/data/data.py@@ -216,4 +216,9 @@ def sanitize_json_bigint(else:as_json = data- return dumps(convert_bigint(as_json), indent=None, separators=(",", ":"))+ return dumps(+ convert_bigint(as_json),+ indent=None,+ separators=(",", ":"),+ default=str,+ )diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pyindex 5e37f62997..b91a2e37a8 100644--- a/marimo/_plugins/core/media.py+++ b/marimo/_plugins/core/media.py@@ -129,7 +129,7 @@ def io_to_data_url(# Handle Pandas DataFrames (convert to CSV)if can_narwhalify(src, eager_only=True):- df = nw.from_native(src, strict=True, eager_only=True)+ df = nw.from_native(src, pass_through=False, eager_only=True)file = io.BytesIO()df.write_csv(file)file.seek(0)diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.pyindex 307c8125c7..eb3200c3db 100644--- a/marimo/_plugins/ui/_impl/data_editor.py+++ b/marimo/_plugins/ui/_impl/data_editor.py@@ -267,9 +267,8 @@ def _apply_edits_dataframe(column_oriented = df.to_dict(as_series=False)schema = schema or cast(nw.Schema, df.schema)new_data = _apply_edits_column_oriented(column_oriented, edits, schema)- native_namespace = nw.get_native_namespace(df)new_native_df = nw.from_dict(- new_data, native_namespace=native_namespace+ new_data, backend=nw.get_native_namespace(df)).to_native()return new_native_df # type: ignore[no-any-return]diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex 7478b971e0..835ae07d27 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -292,16 +292,6 @@ class DefaultTableManager(TableManager[JsonTableData]):)top_k = sorted_grouped[:k]- chosen_column_name = None- for column_name in ["count", "number of rows", "count of rows"]:- if column_name not in column_names:- chosen_column_name = column_name- break- if chosen_column_name is None:- raise ValueError(- "Cannot specify a count column name, please rename your column"- )-return [(value, count) for value, count in top_k]def get_field_type(diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex e29111b527..a2d4e40b1e 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -30,10 +30,12 @@ from marimo._utils.narwhals_utils import (can_narwhalify,dataframe_to_csv,is_narwhals_integer_type,+ is_narwhals_lazyframe,is_narwhals_string_type,is_narwhals_temporal_type,is_narwhals_time_type,unwrap_py_scalar,+ upgrade_narwhals_df,)LOGGER = _loggers.marimo_logger()@@ -46,13 +48,21 @@ class NarwhalsTableManager(@staticmethoddef from_dataframe(data: IntoFrameT) -> NarwhalsTableManager[IntoFrameT]:- return NarwhalsTableManager(nw.from_native(data, strict=True))+ return NarwhalsTableManager(nw.from_native(data, pass_through=False))def as_frame(self) -> nw.DataFrame[Any]:- if isinstance(self.data, nw.LazyFrame):+ if is_narwhals_lazyframe(self.data):return self.data.collect()return self.data+ def upgrade(self) -> NarwhalsTableManager[Any]:+ return NarwhalsTableManager(upgrade_narwhals_df(self.data))++ def as_lazy_frame(self) -> nw.LazyFrame[Any]:+ if is_narwhals_lazyframe(self.data):+ return self.data+ return self.data.lazy()+def with_new_data(self, data: nw.DataFrame[Any] | nw.LazyFrame[Any]) -> TableManager[Any]:@@ -72,18 +82,8 @@ class NarwhalsTableManager(def to_json_str(self, format_mapping: Optional[FormatMapping] = None) -> str:- try:- csv_str = self.to_csv_str(format_mapping=format_mapping)- except Exception as e:- LOGGER.debug(- f"Failed to use format mapping: {str(e)}, falling back to default"- )- csv_str = self.to_csv_str()-- import csv-- csv_reader = csv.DictReader(csv_str.splitlines())- return sanitize_json_bigint([row for row in csv_reader])+ frame = self.upgrade().apply_formatting(format_mapping).as_frame()+ return sanitize_json_bigint(frame.rows(named=True))def to_parquet(self) -> bytes:stream = io.BytesIO()@@ -96,16 +96,15 @@ class NarwhalsTableManager(if not format_mapping:return self- _data = self.as_frame().to_dict(as_series=False).copy()+ frame = self.upgrade().as_frame()+ _data = frame.to_dict(as_series=False).copy()for col in _data.keys():if col in format_mapping:_data[col] = [format_value(col, x, format_mapping) for x in _data[col]]return NarwhalsTableManager(- nw.from_dict(- _data, native_namespace=nw.get_native_namespace(self.data)- )+ nw.from_dict(_data, backend=nw.get_native_namespace(frame)))def supports_filters(self) -> bool:@@ -115,13 +114,14 @@ class NarwhalsTableManager(if not indices:return self.with_new_data(self.data.head(0))- df = self.as_frame()# Prefer the index column for selections- if INDEX_COLUMN_NAME in df.columns:+ if INDEX_COLUMN_NAME in self.nw_schema.names():# Drop the index column before returningreturn self.with_new_data(- df.filter(nw.col(INDEX_COLUMN_NAME).is_in(indices))+ self.data.filter(nw.col(INDEX_COLUMN_NAME).is_in(indices)))++ df = self.as_frame()return self.with_new_data(df[indices])def select_columns(self, columns: list[str]) -> TableManager[Any]:@@ -164,43 +164,25 @@ class NarwhalsTableManager(def calculate_top_k_rows(self, column: ColumnName, k: int) -> list[tuple[Any, int]]:- if isinstance(self.data, nw.LazyFrame):- raise ValueError(- "Cannot calculate top k rows for lazy frames, please collect the data first"- )-- columns = self.get_column_names()-- if column not in columns:+ frame = self.as_lazy_frame()+ if column not in self.get_column_names():raise ValueError(f"Column {column} not found in table.")- # Find a column name for the count that doesn't conflict with existing columns- chosen_column_name: str | None = None- for col in ["count", f"count of {column}", "num_rows"]:- if col not in columns:- chosen_column_name = col- break- if chosen_column_name is None:- raise ValueError(- "Cannot specify a count column name, please rename your column"- )-- # column is also sorted to ensure nulls are last+ _unique_name = "__len_count__"result = (- self.data.group_by(column)- .agg(nw.len().alias(chosen_column_name))- .sort(- [chosen_column_name, column], descending=True, nulls_last=True- )+ frame.group_by(column)+ .agg(nw.len().alias(_unique_name))+ .sort([_unique_name, column], descending=[True, False]).head(k)+ .collect())return [(- unwrap_py_scalar(row[column]),- int(unwrap_py_scalar(row[chosen_column_name])),+ unwrap_py_scalar(row[0]),+ int(unwrap_py_scalar(row[1])),)- for row in result.iter_rows(named=True)+ for row in result.rows()]@staticmethod@@ -302,112 +284,121 @@ class NarwhalsTableManager(# If column is not in the dataframe, return an empty summaryif column not in self.nw_schema:return ColumnSummary()- data = self.data.select(column)- if isinstance(data, nw.LazyFrame):- data = data.collect()-- col = data[column]- total = col.shape[0]- if is_narwhals_string_type(col.dtype):- return ColumnSummary(- total=total,- nulls=col.null_count(),- unique=col.n_unique(),++ frame = self.data.lazy()+ col = nw.col(column)+ dtype = self.nw_schema[column]+ units: dict[str, str] = {}++ # Base expressions for all types+ exprs: dict[str, nw.Expr] = {+ "total": nw.len().alias("total"),+ "nulls": col.null_count(),+ }++ if is_narwhals_string_type(dtype):+ exprs["unique"] = col.n_unique()+ elif dtype == nw.Boolean:+ exprs.update(+ {+ "true": col.sum(), # type: ignore[dict-item]+ "false": nw.len() - col.sum(), # type: ignore[dict-item]+ })- if col.dtype == nw.Boolean:- return ColumnSummary(- total=total,- nulls=col.null_count(),- true=cast(int, col.sum()),- false=cast(int, total - col.sum()),+ elif (dtype == nw.Date) or is_narwhals_time_type(dtype):+ exprs.update(+ {+ "min": col.min(),+ "max": col.max(),+ })- if (col.dtype == nw.Date) or is_narwhals_time_type(col.dtype):# Arrow does not support mean or quantile- if self.data.implementation.is_pyarrow():- return ColumnSummary(- total=total,- nulls=col.null_count(),- min=col.min(),- max=col.max(),- )-- return ColumnSummary(- total=total,- nulls=col.null_count(),- min=col.min(),- max=col.max(),- mean=col.mean(),+ if not frame.implementation.is_pyarrow():+ exprs["mean"] = col.mean()# Quantile not supported on date and time types- # median=col.quantile(0.5, interpolation="nearest"),- )- if col.dtype == nw.Duration and isinstance(col.dtype, nw.Duration):+ # exprs["median"] = col.quantile(0.5, interpolation="nearest")++ elif dtype == nw.Duration and isinstance(dtype, nw.Duration):unit_map = {"ms": (col.dt.total_milliseconds, "ms"),"ns": (col.dt.total_nanoseconds, "ns"),"us": (col.dt.total_microseconds, "μs"),"s": (col.dt.total_seconds, "s"),}- method, unit = unit_map[col.dtype.time_unit]+ method, unit = unit_map[dtype.time_unit]res = method()- return ColumnSummary(- total=total,- nulls=col.null_count(),- min=str(res.min()) + unit,- max=str(res.max()) + unit,- mean=str(res.mean()) + unit,+ exprs.update(+ {+ "min": res.min(),+ "max": res.max(),+ "mean": res.mean(),+ }+ )+ units.update(+ {+ "min": unit,+ "max": unit,+ "mean": unit,+ }+ )+ elif is_narwhals_temporal_type(dtype):+ exprs.update(+ {+ "min": col.min(),+ "max": col.max(),+ })- if is_narwhals_temporal_type(col.dtype):# Arrow does not support mean or quantile- if self.data.implementation.is_pyarrow():- return ColumnSummary(- total=total,- nulls=col.null_count(),- min=col.min(),- max=col.max(),+ if not frame.implementation.is_pyarrow():+ exprs.update(+ {+ "mean": col.mean(),+ "median": col.quantile(0.5, interpolation="nearest"),+ "p5": col.quantile(0.05, interpolation="nearest"),+ "p25": col.quantile(0.25, interpolation="nearest"),+ "p75": col.quantile(0.75, interpolation="nearest"),+ "p95": col.quantile(0.95, interpolation="nearest"),+ })- return ColumnSummary(- total=total,- nulls=col.null_count(),- min=col.min(),- max=col.max(),- mean=col.mean(),- median=col.quantile(0.5, interpolation="nearest"),- p5=col.quantile(0.05, interpolation="nearest"),- p25=col.quantile(0.25, interpolation="nearest"),- p75=col.quantile(0.75, interpolation="nearest"),- p95=col.quantile(0.95, interpolation="nearest"),+ elif is_narwhals_integer_type(dtype):+ exprs.update(+ {+ "unique": col.n_unique(),+ "min": col.min(),+ "max": col.max(),+ "mean": col.mean(),+ "median": col.quantile(0.5, interpolation="nearest"),+ "std": col.std(),+ "p5": col.quantile(0.05, interpolation="nearest"),+ "p25": col.quantile(0.25, interpolation="nearest"),+ "p75": col.quantile(0.75, interpolation="nearest"),+ "p95": col.quantile(0.95, interpolation="nearest"),+ })- if (- col.dtype == nw.List- or col.dtype == nw.Struct- or col.dtype == nw.Object- or col.dtype == nw.Array- ):- return ColumnSummary(- total=total,- nulls=col.null_count(),- )- if col.dtype == nw.Unknown:- return ColumnSummary(- total=total,- nulls=col.null_count(),+ elif dtype.is_numeric():+ exprs.update(+ {+ "min": col.min(),+ "max": col.max(),+ "mean": col.mean(),+ "median": col.quantile(0.5, interpolation="nearest"),+ "std": col.std(),+ "p5": col.quantile(0.05, interpolation="nearest"),+ "p25": col.quantile(0.25, interpolation="nearest"),+ "p75": col.quantile(0.75, interpolation="nearest"),+ "p95": col.quantile(0.95, interpolation="nearest"),+ })- return ColumnSummary(- total=total,- nulls=col.null_count(),- unique=(- col.n_unique() if is_narwhals_integer_type(col.dtype) else None- ),- min=col.min(),- max=col.max(),- mean=col.mean(),- median=col.quantile(0.5, interpolation="nearest"),- std=col.std(),- p5=col.quantile(0.05, interpolation="nearest"),- p25=col.quantile(0.25, interpolation="nearest"),- p75=col.quantile(0.75, interpolation="nearest"),- p95=col.quantile(0.95, interpolation="nearest"),- )++ summary = frame.select(**exprs)+ summary_dict = summary.collect().rows(named=True)[0]++ # Maybe add units to the summary+ for key, value in summary_dict.items():+ if key in units:+ summary_dict[key] = f"{value} {units[key]}"++ return ColumnSummary(**summary_dict)def get_num_rows(self, force: bool = True) -> Optional[int]:# If force is true, collect the data and get the number of rows@@ -415,7 +406,7 @@ class NarwhalsTableManager(return self.as_frame().shape[0]# When lazy, we don't know the number of rows- if isinstance(self.data, nw.LazyFrame):+ if is_narwhals_lazyframe(self.data):return None# Otherwise, we can get the number of rows from the shape@@ -435,17 +426,20 @@ class NarwhalsTableManager(return column_namesdef get_unique_column_values(self, column: str) -> list[str | int | float]:+ frame = self.data.select(nw.col(column))+ if isinstance(frame, nw.LazyFrame):+ frame = frame.collect()try:- return self.data[column].unique().to_list()+ return frame[column].unique().to_list()except BaseException:# Catch-all: some libraries like Polars have bugs and raise# BaseExceptions, which shouldn't crash the kernel# If an exception occurs, try converting to strings first- return self.data[column].cast(nw.String).unique().to_list()+ return frame[column].cast(nw.String).unique().to_list()def get_sample_values(self, column: str) -> list[str | int | float]:# Skip lazy frames- if isinstance(self.data, nw.LazyFrame):+ if is_narwhals_lazyframe(self.data):return []# Sample 3 values from the column@@ -487,7 +481,7 @@ class NarwhalsTableManager(def sort_values(self, by: ColumnName, descending: bool) -> TableManager[Any]:- if isinstance(self.data, nw.LazyFrame):+ if is_narwhals_lazyframe(self.data):return self.with_new_data(self.data.sort(by, descending=descending, nulls_last=True))diff --git a/marimo/_plugins/ui/_impl/tables/selection.py b/marimo/_plugins/ui/_impl/tables/selection.pyindex 72b66c2c85..1d8b98d585 100644--- a/marimo/_plugins/ui/_impl/tables/selection.py+++ b/marimo/_plugins/ui/_impl/tables/selection.py@@ -13,7 +13,7 @@ T = TypeVar("T")def add_selection_column(data: T) -> tuple[T, bool]:if nw.dependencies.is_into_dataframe(data):- df = nw.from_native(cast(IntoDataFrame, data), strict=True)+ df = nw.from_native(cast(IntoDataFrame, data), pass_through=False)if INDEX_COLUMN_NAME not in df.columns:return df.with_row_index(name=INDEX_COLUMN_NAME).to_native(), True # type: ignore[return-value]return data, True # already has a row index@@ -22,7 +22,7 @@ def add_selection_column(data: T) -> tuple[T, bool]:def remove_selection_column(data: T) -> T:if nw.dependencies.is_into_dataframe(data):- df = nw.from_native(cast(IntoDataFrame, data), strict=True)+ df = nw.from_native(cast(IntoDataFrame, data), pass_through=False)if INDEX_COLUMN_NAME in df.columns:return df.drop(INDEX_COLUMN_NAME).to_native() # type: ignore[return-value]return datadiff --git a/marimo/_smoke_tests/theming/custom_css.py b/marimo/_smoke_tests/theming/custom_css.pyindex 38fa846f04..71cd5a7e6d 100644--- a/marimo/_smoke_tests/theming/custom_css.py+++ b/marimo/_smoke_tests/theming/custom_css.py@@ -8,7 +8,7 @@import marimo-__generated_with = "0.11.5"+__generated_with = "0.13.10"app = marimo.App(width="medium", css_file="custom.css")@@ -41,10 +41,10 @@ def _(mo):def _(mo):mo.md(r"""- # heading+ # heading- Here is a paragraph- """+ Here is a paragraph+ """)returndiff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.pyindex 057492cb96..a295c260f4 100644--- a/marimo/_utils/narwhals_utils.py+++ b/marimo/_utils/narwhals_utils.py@@ -2,8 +2,9 @@from __future__ import annotationsimport sys-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Union, overload+import narwhals as nw_mainimport narwhals.dtypes as nw_dtypesimport narwhals.stable.v1 as nw@@ -17,15 +18,16 @@ else:if TYPE_CHECKING:from narwhals.typing import IntoFrame+ from typing_extensions import TypeIsdef empty_df(native_df: IntoFrame) -> IntoFrame:"""Get an empty dataframe with the same schema as the given dataframe."""- if can_narwhalify(native_df, eager_only=True):- df = nw.from_native(native_df, eager_only=True)- return df[[]].to_native()+ if can_narwhalify(native_df):+ df = nw.from_native(native_df)+ return df.head(0).to_native()return native_df@@ -33,7 +35,7 @@ def assert_narwhals_dataframe(df: nw.DataFrame[Any]) -> None:"""Assert that the given dataframe is a valid narwhals dataframe."""- if not isinstance(df, nw.DataFrame):+ if not is_narwhals_dataframe(df):raise ValueError(f"Unsupported dataframe type. Got {type(df)}")@@ -74,17 +76,11 @@ def dataframe_to_csv(df: IntoFrame) -> str:"""assert_can_narwhalify(df)df = nw.from_native(df, strict=True)- if isinstance(df, nw.LazyFrame):- return str(df.collect().write_csv())- if nw.get_level(df) == "interchange":- # `write_csv` isn't supported by interchange-level-only- # DataFrames, so we convert to PyArrow in this case- csv_str = nw.from_native(df.to_arrow(), eager_only=True).write_csv()+ df = upgrade_narwhals_df(df)+ if is_narwhals_lazyframe(df):+ return df.collect().write_csv()else:- csv_str = df.write_csv()- if isinstance(csv_str, bytes):- return csv_str.decode("utf-8")- return str(csv_str)+ return df.write_csv()def is_narwhals_integer_type(@@ -134,9 +130,9 @@ def unwrap_narwhals_dataframe(df: Any) -> Any:"""Unwrap a narwhals dataframe."""- if isinstance(df, nw.DataFrame):+ if is_narwhals_dataframe(df):return df.to_native() # type: ignore[return-value]- if isinstance(df, nw.LazyFrame):+ if is_narwhals_lazyframe(df):return df.to_native() # type: ignore[return-value]return df@@ -177,3 +173,38 @@ def can_narwhalify_lazyframe(df: Any) -> TypeGuard[Any]:return isinstance(df, duckdb.DuckDBPyRelation)return False+++@overload+def upgrade_narwhals_df(df: nw.DataFrame[Any]) -> nw.DataFrame[Any]: ...+++@overload+def upgrade_narwhals_df(df: nw.LazyFrame[Any]) -> nw.LazyFrame[Any]: ...+++def upgrade_narwhals_df(+ df: Union[nw.DataFrame[Any], nw.LazyFrame[Any]],+) -> Union[nw.DataFrame[Any], nw.LazyFrame[Any]]:+ """+ Upgrade a narwhals dataframe to the latest version.+ """+ return nw_main.from_native(df.to_native()) # type: ignore[no-any-return]+++def is_narwhals_lazyframe(df: Any) -> TypeIs[nw.LazyFrame[Any]]:+ """+ Check if the given object is a narwhals lazyframe.++ Checks both v1 and main.+ """+ return isinstance(df, nw.LazyFrame) or isinstance(df, nw_main.LazyFrame)+++def is_narwhals_dataframe(df: Any) -> TypeIs[nw.DataFrame[Any]]:+ """+ Check if the given object is a narwhals dataframe.++ Checks both v1 and main.+ """+ return isinstance(df, nw.DataFrame) or isinstance(df, nw_main.DataFrame)diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.pyindex 8f5124c733..02a7a52153 100644--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py@@ -105,7 +105,7 @@ def test_data_to_csv_string(df: IntoDataFrame):assert isinstance(result, str)lines = result.strip().split("\n")assert len(lines) == 4 # header + 3 data rows- assert lines[0] == "A,B" or lines[0] == "A,B\r"+ assert lines[0].startswith('"A","B"') or lines[0].startswith("A,B")@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@@ -161,13 +161,9 @@ def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):# Verify the content of the inline CSVbase64_data = result["url"].split(",")[1]decoded_data = base64.b64decode(base64_data).decode("utf-8")- assert decoded_data.startswith("A,B")- assert (- decoded_data.endswith("9999,value_9999\n")- or- # for windows- decoded_data.endswith("9999,value_9999\r\n")- )+ assert decoded_data.startswith('"A","B"') or decoded_data.startswith("A,B")+ lines = decoded_data.strip().split("\n")+ assert len(lines) == 10001 # header + 10000 data rows@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")diff --git a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.json b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.jsonnew file mode 100644index 0000000000..4cc2c1fdb9--- /dev/null+++ b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.json@@ -0,0 +1,56 @@+[+ {+ "strings": "a",+ "bool": true,+ "int": 1,+ "float": 1.0,+ "datetime": "2021-01-01 00:00:00",+ "date": "2021-01-01",+ "struct": { "a": 1, "b": 2 },+ "list": [1, 2],+ "array": [1],+ "nulls": null,+ "category": "cat",+ "set": "{1, 2}",+ "imaginary": "(1+2j)",+ "time": "12:30:00",+ "duration": "1 day, 0:00:00",+ "mixed_list": ["1", "two"]+ },+ {+ "strings": "b",+ "bool": false,+ "int": 2,+ "float": 2.0,+ "datetime": "2021-01-02 00:00:00",+ "date": "2021-01-02",+ "struct": { "a": 3, "b": 4 },+ "list": [3, 4],+ "array": [2],+ "nulls": "data",+ "category": "dog",+ "set": "{3, 4}",+ "imaginary": "(3+4j)",+ "time": "13:45:00",+ "duration": "2 days, 0:00:00",+ "mixed_list": ["3.0", "0.0"]+ },+ {+ "strings": "c",+ "bool": true,+ "int": 3,+ "float": 3.0,+ "datetime": "2021-01-03 00:00:00",+ "date": "2021-01-03",+ "struct": { "a": 5, "b": 6 },+ "list": [5, 6],+ "array": [3],+ "nulls": null,+ "category": "mouse",+ "set": "{5, 6}",+ "imaginary": "(5+6j)",+ "time": "14:15:00",+ "duration": "3 days, 0:00:00",+ "mixed_list": [null, "2021-01-01 00:00:00.000000"]+ }+]diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex 6005bb97a6..f372e564fa 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -25,6 +25,7 @@ from marimo._utils.narwhals_utils import unwrap_py_scalarfrom tests._data.mocks import (EAGER_LIBS,NON_EAGER_LIBS,+ DFType,create_dataframes,)from tests.mocks import snapshotter@@ -33,6 +34,15 @@ HAS_DEPS = DependencyManager.polars.has()snapshot = snapshotter(__file__)+SUPPORTED_LIBS: list[DFType] = [+ "pandas",+ "polars",+ # TODO: Either we can import narwhals `main` or wait for v0.1.0+ # "ibis",+ "lazy-polars",+ "pyarrow",+]+def assert_frame_equal(a: Any, b: Any) -> None:return a.to_dict() == b.to_dict()@@ -146,21 +156,18 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):)def test_to_csv_complex(self) -> None:complex_data = self.get_complex_data()- data = complex_data.to_csv()- assert isinstance(data, bytes)- snapshot("narwhals.csv", data.decode("utf-8"))+ data = complex_data.to_csv_str()+ assert isinstance(data, str)+ snapshot("narwhals.csv", data)def test_to_json(self) -> None:assert isinstance(self.manager.to_json(), bytes)- @pytest.mark.xfail(- reason="Narwhals (polars) doesn't support writing nested lists to csv"- )def test_to_json_complex(self) -> None:complex_data = self.get_complex_data()- data = complex_data.to_json()- assert isinstance(data, bytes)- snapshot("narwhals.json", data.decode("utf-8"))+ data = complex_data.to_json_str()+ assert isinstance(data, str)+ snapshot("narwhals.json", data)def test_complex_data_field_types(self) -> None:complex_data = self.get_complex_data()@@ -724,31 +731,34 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):)assert_frame_equal(formatted_data, expected_data)- def test_to_json_bigint(self) -> None:- import polars as pl- data = pl.DataFrame(- {- "A": [- 20,- 9007199254740992,- ], # MAX_SAFE_INTEGER and MAX_SAFE_INTEGER + 1- "B": [- -20,- -9007199254740992,- ], # MIN_SAFE_INTEGER and MIN_SAFE_INTEGER - 1- }- )- manager = NarwhalsTableManager.from_dataframe(data)- json_data = json.loads(manager.to_json())[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ create_dataframes(+ {+ "A": [+ 20,+ 9007199254740992,+ ], # MAX_SAFE_INTEGER and MAX_SAFE_INTEGER + 1+ "B": [+ -20,+ -9007199254740992,+ ], # MIN_SAFE_INTEGER and MIN_SAFE_INTEGER - 1+ },+ include=SUPPORTED_LIBS,+ ),+)+def test_to_json_bigint(df: Any) -> None:+ manager = NarwhalsTableManager.from_dataframe(df)+ json_data = json.loads(manager.to_json())- # These get converted to strings because narwhals uses csv parsing- assert json_data[0]["A"] == "20"- assert json_data[0]["B"] == "-20"+ assert json_data[0]["A"] == 20+ assert json_data[0]["B"] == -20- # Large integers should be converted to strings- assert json_data[1]["A"] == "9007199254740992"- assert json_data[1]["B"] == "-9007199254740992"+ # Large integers should be converted to strings+ assert json_data[1]["A"] == "9007199254740992"+ assert json_data[1]["B"] == "-9007199254740992"@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@@ -760,6 +770,7 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):"B": ["a", "b", "c"],"C": [1.0, 2.0, 3.0],},+ include=SUPPORTED_LIBS,),)def test_to_csv(df: Any) -> None:@@ -800,17 +811,10 @@ def test_to_json(df: Any) -> None:assert isinstance(manager.to_json(), bytes)- reason="Format mapping is not supported when converting to JSON"-)@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",- create_dataframes(- {- "A": [1, 2, 3],- }- ),+ create_dataframes({"A": [1, 2, 3]}),)def test_to_json_format_mapping(df: Any) -> None:format_mapping = {"A": lambda x: x * 2}@@ -1049,22 +1053,22 @@ def test_get_sample_values(df: Any) -> None:"df",create_dataframes({- "A": [1, 2, 3, 3, None, None],- "B": [4, 5, 6, 6, None, None],+ "A": [1, 2, 3, 3, 3, None, None],+ "B": [4, 5, 6, 6, 6, None, None],},- include=["pandas", "polars"],+ include=SUPPORTED_LIBS,),)def test_calculate_top_k_rows(df: Any) -> None:manager = NarwhalsTableManager.from_dataframe(df)result = manager.calculate_top_k_rows("A", 10)normalized_result = _normalize_result(result)- assert normalized_result == [(3, 2), (None, 2), (2, 1), (1, 1)]+ assert normalized_result == [(3, 3), (None, 2), (1, 1), (2, 1)]# Test with limitresult = manager.calculate_top_k_rows("A", 2)normalized_result = _normalize_result(result)- assert normalized_result == [(3, 2), (None, 2)]+ assert normalized_result == [(3, 3), (None, 2)]@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@@ -1072,7 +1076,7 @@ def test_calculate_top_k_rows(df: Any) -> None:"df",create_dataframes({"count": [1, 2, 3, 3, None, None]},- include=["pandas", "polars"],+ include=SUPPORTED_LIBS,),)def test_calculate_top_k_rows_conflicting_colname(df: Any) -> None:@@ -1081,19 +1085,7 @@ def test_calculate_top_k_rows_conflicting_colname(df: Any) -> None:# Test original column Aresult_a = manager.calculate_top_k_rows("count", 10)normalized_result_a = _normalize_result(result_a)- assert normalized_result_a == [(3, 2), (None, 2), (2, 1), (1, 1)]--[email protected](not HAS_DEPS, reason="optional dependencies not installed")-def test_calculate_top_k_rows_lazy_frame() -> None:- import polars as pl-- df = pl.DataFrame({"A": [1, 2, 3, 3, None, None]}).lazy()- manager = NarwhalsTableManager.from_dataframe(df)- with pytest.raises(- ValueError, match="Cannot calculate top k rows for lazy frames"- ):- manager.calculate_top_k_rows("A", 10)+ assert normalized_result_a == [(None, 2), (3, 2), (1, 1), (2, 1)]@pytest.mark.xfail(@@ -1234,52 +1226,58 @@ def test_get_field_types_with_many_columns_is_performant(df: Any) -> None:@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")-class TestCalculateTopKRowsCaching(unittest.TestCase):- def setUp(self) -> None:- import polars as pl-- self.data = pl.DataFrame(- {"name": ["Alice", "Eve", None], "age": [25, 35, None]}- )- self.manager = NarwhalsTableManager.from_dataframe(self.data)+ "df",+ create_dataframes({"name": ["Alice", "Eve", None], "age": [25, 35, None]}),+)+def test_calculate_top_k_rows_caching(df: Any) -> None:+ manager = NarwhalsTableManager.from_dataframe(df)+ """Test that calculate_top_k_rows caching works correctly."""+ # First call should compute the result+ result1 = manager.calculate_top_k_rows("name", 10)- def test_calculate_top_k_rows_caching(self) -> None:- """Test that calculate_top_k_rows caching works correctly."""- # First call should compute the result- result1 = self.manager.calculate_top_k_rows("name", 10)+ # Second call with same args should use cache and return same object+ result2 = manager.calculate_top_k_rows("name", 10)+ assert result1 is result2- # Second call with same args should use cache and return same object- result2 = self.manager.calculate_top_k_rows("name", 10)- assert result1 is result2+ # Different k value should compute new result+ result3 = manager.calculate_top_k_rows("name", 5)+ assert result3 is not result1- # Different k value should compute new result- result3 = self.manager.calculate_top_k_rows("name", 5)- assert result3 is not result1+ # Different column name should compute new result+ result4 = manager.calculate_top_k_rows("age", 10)+ assert result4 is not result1- # Different column name should compute new result- result4 = self.manager.calculate_top_k_rows("age", 10)- assert result4 is not result1- def test_calculate_top_k_rows_cache_invalidation(self) -> None:- """Test that cache is properly invalidated when data changes."""- # Initial calculation- result1 = self.manager.calculate_top_k_rows("name", 2)[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ "df",+ create_dataframes(+ {"name": ["Alice", "Eve", None], "age": [25, 35, None]},+ exclude=["ibis", "duckdb"],+ ),+)+def test_calculate_top_k_rows_cache_invalidation(df: Any) -> None:+ """Test that cache is properly invalidated when data changes."""+ manager = NarwhalsTableManager.from_dataframe(df)- # Modify the data- import polars as pl+ # Initial calculation+ result1 = manager.calculate_top_k_rows("name", 2)- new_data = pl.DataFrame(- {- "name": ["Alice", "Eve", "Bob", None],- }- )+ # Modify the data+ new_data = nw.from_dict(+ {+ "name": ["Alice", "Alice", "Eve", "Bob", None],+ },+ backend=nw.get_native_namespace(manager.as_frame()),+ )- # Create a new manager with the new data- self.manager = NarwhalsTableManager.from_dataframe(new_data)+ # Create a new manager with the new data+ manager = NarwhalsTableManager.from_dataframe(new_data)- # New calculation should be performed and return different result- result2 = self.manager.calculate_top_k_rows("name", 2)- assert result2 is not result1 # Different result due to data change+ # New calculation should be performed and return different result+ result2 = manager.calculate_top_k_rows("name", 2)+ assert result2 is not result1 # Different result due to data change- # Verify the actual results are different- assert result1 != result2+ # Verify the actual results are different+ assert result1 != result2diff --git a/tests/_plugins/ui/_impl/tables/test_selection.py b/tests/_plugins/ui/_impl/tables/test_selection.pyindex 97fc35b4f0..c769793718 100644--- a/tests/_plugins/ui/_impl/tables/test_selection.py+++ b/tests/_plugins/ui/_impl/tables/test_selection.py@@ -41,7 +41,7 @@ def test_selection_with_index_column(backend: Any):"name": ["Alice", "Bob", "Charlie"],"age": [30, 25, 35],},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -63,7 +63,7 @@ def test_selection_with_index_column_and_sort(backend: Any):"name": ["Alice", "Bob", "Charlie"],"age": [30, 25, 35],},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -86,7 +86,7 @@ def test_selection_with_index_column_and_search(backend: Any):"name": ["Alice", "Bob", "Charlie"],"age": [30, 25, 35],},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -105,7 +105,7 @@ def test_selection_with_index_column_empty(backend: Any):# Create test data with index columndata = nw.from_dict({INDEX_COLUMN_NAME: [0, 1], "name": ["Alice", "Bob"], "age": [30, 25]},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -123,7 +123,7 @@ def test_selection_without_index_column(backend: Any):# Create test data without index columndata = nw.from_dict({"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -145,7 +145,7 @@ def test_selection_with_index_column_take(backend: Any):"name": ["Alice", "Bob", "Charlie", "Dave", "Eve"],"age": [30, 25, 35, 28, 22],},- native_namespace=backend,+ backend=backend,)manager = NarwhalsTableManager(data)@@ -162,7 +162,7 @@ def test_selection_with_index_column_take(backend: Any):def test_add_selection_to_dataframe(backend: Any):data = nw.from_dict({"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},- native_namespace=backend,+ backend=backend,)with_selection, has_stable_row_id = add_selection_column(data.to_native())@@ -183,7 +183,7 @@ def test_add_selection_to_dataframe_already_has_index(backend: Any):"name": ["Alice", "Bob", "Charlie"],"age": [30, 25, 35],},- native_namespace=backend,+ backend=backend,)with_selection, has_stable_row_id = add_selection_column(data.to_native())@@ -200,7 +200,7 @@ def test_add_selection_to_dataframe_already_has_index(backend: Any):def test_remove_selection_column(backend: Any):data = nw.from_dict({"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},- native_namespace=backend,+ backend=backend,)with_selection, has_stable_row_id = add_selection_column(data.to_native())assert has_stable_row_id is Truediff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex e8b0131f6e..e044e38816 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -151,7 +151,7 @@ class TestAltairChart:) -> None:assert (nw.Datetime- == nw.from_native(df, strict=True).schema["datetime_column"]+ == nw.from_native(df, pass_through=False).schema["datetime_column"])# Define an interval selectiondiff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.pyindex 4cab08343c..66e9906e6d 100644--- a/tests/_utils/test_narwhals_utils.py+++ b/tests/_utils/test_narwhals_utils.py@@ -14,10 +14,12 @@ from marimo._utils.narwhals_utils import (dataframe_to_csv,empty_df,is_narwhals_integer_type,+ is_narwhals_lazyframe,is_narwhals_string_type,is_narwhals_temporal_type,unwrap_narwhals_dataframe,unwrap_py_scalar,+ upgrade_narwhals_df,)from tests._data.mocks import create_dataframes@@ -31,14 +33,18 @@ if TYPE_CHECKING:"df",create_dataframes({"a": [1, 2, 3], "b": ["x", "y", "z"]},- exclude=["ibis", "duckdb", "lazy-polars"],),)@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")def test_empty_df(df: IntoDataFrame) -> None:empty: Any = empty_df(df)- assert len(empty) == 0- assert len(empty.columns) == 2++ # Assert shape is empty+ n_df = upgrade_narwhals_df(nw.from_native(empty))+ if is_narwhals_lazyframe(n_df):+ n_df = n_df.collect()++ assert n_df.shape == (0, 2)@pytest.mark.parametrize(