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.

improvement: simplify narwhals utils (#4143)

Myles Scolnickaa6f3f12f5e4
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index 0d28d6e9fc..1785ff7fc1 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -27,6 +27,7 @@ from marimo._utils.narwhals_utils import (
is_narwhals_integer_type,
is_narwhals_string_type,
is_narwhals_temporal_type,
+ is_narwhals_time_type,
unwrap_py_scalar,
)
@@ -149,12 +150,18 @@ class NarwhalsTableManager(
return ("string", dtype_string)
elif dtype == nw.Boolean:
return ("boolean", dtype_string)
- elif is_narwhals_integer_type(dtype):
- return ("integer", dtype_string)
- elif is_narwhals_temporal_type(dtype):
- return ("date", dtype_string)
elif dtype == nw.Duration:
return ("number", dtype_string)
+ elif dtype.is_integer():
+ return ("integer", dtype_string)
+ elif is_narwhals_time_type(dtype):
+ return ("time", dtype_string)
+ elif dtype == nw.Date:
+ return ("date", dtype_string)
+ elif dtype == nw.Datetime:
+ return ("datetime", dtype_string)
+ elif dtype.is_temporal():
+ return ("datetime", dtype_string)
elif dtype.is_numeric():
return ("number", dtype_string)
else:
@@ -185,7 +192,6 @@ class NarwhalsTableManager(
elif (
dtype.is_numeric()
or is_narwhals_temporal_type(dtype)
- or dtype == nw.Duration
or dtype == nw.Boolean
):
expressions.append(
@@ -228,9 +234,7 @@ class NarwhalsTableManager(
true=cast(int, col.sum()),
false=cast(int, total - col.sum()),
)
- if (col.dtype == nw.Date) or (
- getattr(nw, "Time", None) is not None and col.dtype == nw.Time # type: ignore[attr-defined]
- ):
+ if (col.dtype == nw.Date) or is_narwhals_time_type(col.dtype):
return ColumnSummary(
total=total,
nulls=col.null_count(),
@@ -240,19 +244,6 @@ class NarwhalsTableManager(
# Quantile not supported on date and time types
# median=col.quantile(0.5, interpolation="nearest"),
)
- if is_narwhals_temporal_type(col.dtype):
- 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"),
- )
if col.dtype == nw.Duration and isinstance(col.dtype, nw.Duration):
unit_map = {
"ms": (col.dt.total_milliseconds, "ms"),
@@ -269,6 +260,19 @@ class NarwhalsTableManager(
max=str(res.max()) + unit,
mean=str(res.mean()) + unit,
)
+ if is_narwhals_temporal_type(col.dtype):
+ 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"),
+ )
if (
col.dtype == nw.List
or col.dtype == nw.Struct
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index 06a510ca18..cde9859d3e 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import sys
from typing import TYPE_CHECKING, Any
+import narwhals.dtypes as nw_dtypes
import narwhals.stable.v1 as nw
if sys.version_info < (3, 11):
@@ -86,38 +87,34 @@ def dataframe_to_csv(df: IntoFrame) -> str:
def is_narwhals_integer_type(
dtype: Any,
-) -> TypeGuard[
- nw.Int64
- | nw.UInt64
- | nw.Int32
- | nw.UInt32
- | nw.Int16
- | nw.UInt16
- | nw.Int8
- | nw.UInt8
-]:
+) -> TypeGuard[nw_dtypes.IntegerType]:
"""
Check if the given dtype is integer type.
"""
- return bool(
- dtype == nw.Int64
- or dtype == nw.UInt64
- or dtype == nw.Int32
- or dtype == nw.UInt32
- or dtype == nw.Int16
- or dtype == nw.UInt16
- or dtype == nw.Int8
- or dtype == nw.UInt8
- )
+ if hasattr(dtype, "is_integer"):
+ return dtype.is_integer() # type: ignore[no-any-return]
+ return False
def is_narwhals_temporal_type(
dtype: Any,
-) -> TypeGuard[nw.Datetime | nw.Date]:
+) -> TypeGuard[nw_dtypes.TemporalType]:
"""
Check if the given dtype is temporal type.
"""
- return bool(dtype == nw.Datetime or dtype == nw.Date)
+ if hasattr(dtype, "is_temporal"):
+ return dtype.is_temporal() # type: ignore[no-any-return]
+ return False
+
+
+def is_narwhals_time_type(dtype: Any) -> bool:
+ """
+ Check if the given dtype is Time
+ This was added in later version, so we need to safely check
+ """
+ if getattr(nw, "Time", None) is not None:
+ return dtype == nw.Time # type: ignore[attr-defined,no-any-return]
+ return False
def is_narwhals_string_type(
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json
index 3e928d9978..eb085865ac 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json
@@ -3,7 +3,7 @@
["bool", ["boolean", "Boolean"]],
["int", ["integer", "Int64"]],
["float", ["number", "Float64"]],
- ["datetime", ["date", "Datetime(time_unit='us', time_zone=None)"]],
+ ["datetime", ["datetime", "Datetime(time_unit='us', time_zone=None)"]],
["date", ["date", "Date"]],
["struct", ["unknown", "Struct({'a': Int64, 'b': Int64})"]],
["list", ["unknown", "List(Int64)"]],
@@ -12,7 +12,7 @@
["category", ["string", "Categorical"]],
["set", ["unknown", "Object"]],
["imaginary", ["unknown", "Object"]],
- ["time", ["unknown", "Time"]],
+ ["time", ["time", "Time"]],
["duration", ["number", "Duration(time_unit='us')"]],
["mixed_list", ["unknown", "List(String)"]]
]
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 19b08236e1..a6450e5974 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -220,7 +220,7 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
("B", ("string", "String")),
("C", ("number", "Float64")),
("D", ("boolean", "Boolean")),
- ("E", ("date", "Datetime(time_unit='us', time_zone=None)")),
+ ("E", ("datetime", "Datetime(time_unit='us', time_zone=None)")),
]
assert self.manager.get_field_types() == expected_field_types
@@ -258,7 +258,7 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
("E", ("unknown", "Object")),
("F", ("unknown", "Unknown")),
("G", ("unknown", "Object")),
- ("H", ("date", "Datetime(time_unit='us', time_zone=None)")),
+ ("H", ("datetime", "Datetime(time_unit='us', time_zone=None)")),
("I", ("string", "String")),
("J", ("string", "String")),
]
diff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.py
index 4fc0ab20e5..04fb72a7f8 100644
--- a/tests/_utils/test_narwhals_utils.py
+++ b/tests/_utils/test_narwhals_utils.py
@@ -89,8 +89,8 @@ def test_narwhals_type_checks():
assert is_narwhals_temporal_type(nw.Datetime)
assert is_narwhals_temporal_type(nw.Date)
+ assert is_narwhals_temporal_type(nw.Duration)
assert not is_narwhals_temporal_type(nw.Int64)
- assert not is_narwhals_temporal_type(nw.Duration)
assert is_narwhals_string_type(nw.String)
assert is_narwhals_string_type(nw.Categorical)