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: support dates in data-editor (#2619)
Myles Scolnick11cf7139247c
diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.pyindex ca7a4305d8..9de44b4fe2 100644--- a/marimo/_plugins/core/json_encoder.py+++ b/marimo/_plugins/core/json_encoder.py@@ -40,6 +40,10 @@ class WebComponentEncoder(JSONEncoder):if isinstance(o, (datetime.datetime, datetime.date, datetime.time)):return o.isoformat()+ # Handle timedelta+ if isinstance(o, datetime.timedelta):+ return str(o)+# Handle UUIDif isinstance(o, UUID):return str(o)diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.pyindex 80302f21d4..2db303b938 100644--- a/marimo/_plugins/ui/_impl/data_editor.py+++ b/marimo/_plugins/ui/_impl/data_editor.py@@ -1,8 +1,11 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import ast+import datetimefrom dataclasses import dataclassfrom typing import (+ TYPE_CHECKING,Any,Callable,Dict,@@ -11,16 +14,23 @@ from typing import (Optional,TypedDict,Union,+ cast,)import narwhals.stable.v1 as nwfrom narwhals.typing import IntoDataFrameimport marimo._output.data.data as mo_data+from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.tables.utils import get_table_manager+LOGGER = _loggers.marimo_logger()++if TYPE_CHECKING:+ from narwhals.dtypes import DType+@dataclassclass DataEditorValue:@@ -163,19 +173,20 @@ class data_editor(def apply_edits(data: Union[RowOrientedData, ColumnOrientedData, IntoDataFrame],edits: DataEdits,+ schema: Optional[nw.Schema] = None,) -> Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]:if len(edits["edits"]) == 0:return data# If row-oriented, apply edits to the dataif isinstance(data, list):- return _apply_edits_row_oriented(data, edits)+ return _apply_edits_row_oriented(data, edits, schema)# If column-oriented, apply edits to the dataelif isinstance(data, dict):- return _apply_edits_column_oriented(data, edits)+ return _apply_edits_column_oriented(data, edits, schema)# narwhalifytry:- return _apply_edits_dataframe(data, edits) # type: ignore[no-any-return]+ return _apply_edits_dataframe(data, edits, schema) # type: ignore[no-any-return]except Exception as e:raise ValueError(f"Data editor does not support this type of data: {type(data)}"@@ -185,13 +196,17 @@ def apply_edits(def _apply_edits_column_oriented(data: ColumnOrientedData,edits: DataEdits,+ schema: Optional[nw.Schema] = None,) -> ColumnOrientedData:for edit in edits["edits"]:column = data[edit["columnId"]]if edit["rowIdx"] >= len(column):# Extend the column with None values up to the new row indexcolumn.extend([None] * (edit["rowIdx"] - len(column) + 1))- column[edit["rowIdx"]] = edit["value"]+ dtype = schema.get(edit["columnId"]) if schema else None+ column[edit["rowIdx"]] = _convert_value(+ edit["value"], column[0] if column else None, dtype+ )return data@@ -199,22 +214,121 @@ def _apply_edits_column_oriented(def _apply_edits_row_oriented(data: RowOrientedData,edits: DataEdits,+ schema: Optional[nw.Schema] = None,) -> RowOrientedData:for edit in edits["edits"]:if edit["rowIdx"] >= len(data):# Create a new row with None values for all columnsnew_row = {col: None for col in data[0].keys()}data.append(new_row)- data[edit["rowIdx"]][edit["columnId"]] = edit["value"]+ original_value = data[0][edit["columnId"]] if data else None+ dtype = schema.get(edit["columnId"]) if schema else None+ data[edit["rowIdx"]][edit["columnId"]] = _convert_value(+ edit["value"], original_value, dtype+ )return data@nw.narwhalifydef _apply_edits_dataframe(- df: nw.DataFrame[Any], edits: DataEdits+ df: nw.DataFrame[Any], edits: DataEdits, schema: Optional[nw.Schema]) -> nw.DataFrame[Any]:column_oriented = df.to_dict(as_series=False)- new_data = _apply_edits_column_oriented(column_oriented, edits)+ 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)return nw.from_dict(new_data, native_namespace=native_namespace)+++def _convert_value(+ value: Any,+ original_value: Any,+ dtype: Optional[DType] = None,+) -> Any:+ try:+ if dtype is not None:+ if dtype == nw.Datetime:+ return datetime.datetime.fromisoformat(value)+ elif dtype == nw.Date:+ return datetime.date.fromisoformat(value)+ elif dtype == nw.Duration:+ return datetime.timedelta(microseconds=float(value))+ elif dtype == nw.Float32:+ return float(value)+ elif dtype == nw.Float64:+ return float(value)+ elif dtype == nw.Int16:+ return int(value)+ elif dtype == nw.Int32:+ return int(value)+ elif dtype == nw.Int64:+ return int(value)+ elif dtype == nw.UInt16:+ return int(value)+ elif dtype == nw.UInt32:+ return int(value)+ elif dtype == nw.UInt64:+ return int(value)+ elif dtype == nw.String:+ return str(value)+ elif dtype == nw.Enum:+ return str(value)+ elif dtype == nw.Categorical:+ return str(value)+ elif dtype == nw.Boolean:+ return bool(value)+ elif dtype == nw.List:+ # Handle list conversion+ if isinstance(value, str):+ # Attempt to parse string as a list+ try:+ return list(ast.literal_eval(value))+ except (ValueError, SyntaxError):+ # If parsing fails, split the string+ return value.split(",")+ elif isinstance(value, list):+ return value # type: ignore+ else:+ # If it's not a string or list, wrap it in a list+ return [value]+ else:+ LOGGER.warning(f"Unsupported dtype: {dtype}")+ return str(value)++ if original_value is None:+ return value++ # Try to convert the value to the original type+ original_type: Any = type(original_value)++ if isinstance(original_value, (int, float)):+ return original_type(value)+ elif isinstance(original_value, str):+ return str(value)+ elif isinstance(original_value, (datetime.date)):+ return datetime.date.fromisoformat(value)+ elif isinstance(original_value, (datetime.datetime)):+ return datetime.datetime.fromisoformat(value)+ elif isinstance(original_value, (datetime.timedelta)):+ return datetime.timedelta(microseconds=float(value))+ elif isinstance(original_value, list):+ # Handle list conversion+ if isinstance(value, str):+ # Attempt to parse string as a list+ try:+ return list(ast.literal_eval(value))+ except (ValueError, SyntaxError):+ # If parsing fails, split the string+ return list(value.split(","))+ elif isinstance(value, list):+ return value # type: ignore[return-value]+ else:+ # If it's not a string or list, wrap it in a list+ return [value]+ else:+ return value+ except ValueError as e:+ LOGGER.error(str(e))+ # If conversion fails, return the original value+ return original_value # type: ignore[return-value]diff --git a/marimo/_smoke_tests/editable_df.py b/marimo/_smoke_tests/editable_df.pyindex 59f8fb3662..71f44155bf 100644--- a/marimo/_smoke_tests/editable_df.py+++ b/marimo/_smoke_tests/editable_df.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.9.4"+__generated_with = "0.9.9"app = marimo.App(width="medium")@@ -91,17 +91,28 @@ def __(mo):@app.celldef __(pd):+ import datetime+large_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."varying_data = {"strings": ["a", "b", "c", large_text],"numbers": [1, 2, 3, 4],"bools": [True, False, True, False],- "dates": [pd.Timestamp("2021-01-01") for _ in range(4)],+ "timestamps": [pd.Timestamp("2021-01-01") for _ in range(4)],+ "dates": [datetime.date(2021, 1, 1) for _ in range(4)],+ "datetimes": [datetime.datetime(2021, 1, 1, 1, 1, 1) for _ in range(4)],+ "duration": [datetime.timedelta(days=2, seconds=13500) for _ in range(4)],"none": [None for _ in range(4)],"lists": [[1, 2], [3, 4], [5, 6], [7, 8]],}- return large_text, varying_data+ return datetime, large_text, varying_data+++def __(pl, varying_data):+ pl.DataFrame(varying_data).schema+ return@app.celldiff --git a/tests/_plugins/core/test_json_encoder.py b/tests/_plugins/core/test_json_encoder.pyindex 2630415630..dd641d0ca5 100644--- a/tests/_plugins/core/test_json_encoder.py+++ b/tests/_plugins/core/test_json_encoder.py@@ -324,6 +324,14 @@ def test_date_time_encoding() -> None:assert encoded_datetime == '"2023-01-01T12:30:45"'+def test_timedelta_encoding() -> None:+ import datetime++ timedelta_obj = datetime.timedelta(days=1, seconds=2, microseconds=3)+ encoded = json.dumps(timedelta_obj, cls=WebComponentEncoder)+ assert encoded == '"1 day, 0:00:02.000003"'++def test_enum_encoding() -> None:from enum import Enumdiff --git a/tests/_plugins/ui/_impl/test_data_editor.py b/tests/_plugins/ui/_impl/test_data_editor.pyindex cca3da0846..c502891404 100644--- a/tests/_plugins/ui/_impl/test_data_editor.py+++ b/tests/_plugins/ui/_impl/test_data_editor.py@@ -1,8 +1,10 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import datetimefrom typing import Any+import narwhals.stable.v1 as nwimport pytestfrom marimo._dependencies.dependencies import DependencyManager@@ -87,6 +89,227 @@ def test_apply_edits_new_row():]+ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_ints_floats():+ data = [{"A": 1, "B": 2.5}, {"A": 3, "B": 4.7}]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "A", "value": "2"},+ {"rowIdx": 1, "columnId": "B", "value": "5.8"},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [{"A": 2, "B": 2.5}, {"A": 3, "B": 5.8}]++ # With dtypes+ result = apply_edits(+ data, edits, schema=nw.Schema({"A": nw.Float32(), "B": nw.Float32()})+ )+ assert result == [{"A": 2.0, "B": 2.5}, {"A": 3.0, "B": 5.8}]+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_booleans():+ data = [{"A": True, "B": False}, {"A": False, "B": True}]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "A", "value": False},+ {"rowIdx": 1, "columnId": "B", "value": False},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [{"A": False, "B": False}, {"A": False, "B": False}]++ # With dtypes+ result = apply_edits(+ data, edits, schema=nw.Schema({"A": nw.Boolean(), "B": nw.Boolean()})+ )+ assert result == [{"A": False, "B": False}, {"A": False, "B": False}]+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_dates():+ data = [+ {"date": datetime.date(2023, 1, 1)},+ {"date": datetime.date(2023, 2, 1)},+ ]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "date", "value": "2023-03-15"},+ {"rowIdx": 1, "columnId": "date", "value": "2023-04-20"},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [+ {"date": datetime.date(2023, 3, 15)},+ {"date": datetime.date(2023, 4, 20)},+ ]++ # With dtypes+ result = apply_edits(data, edits, schema=nw.Schema({"date": nw.Date()}))+ assert result == [+ {"date": datetime.date(2023, 3, 15)},+ {"date": datetime.date(2023, 4, 20)},+ ]+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_lists():+ data = [{"list": [1, 2, 3]}, {"list": [4, 5, 6]}]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "list", "value": "[1, 2, 3, 4]"},+ {"rowIdx": 1, "columnId": "list", "value": "7,8"},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [{"list": [1, 2, 3, 4]}, {"list": [7, 8]}]++ # With dtypes+ result = apply_edits(+ data, edits, schema=nw.Schema({"list": nw.List(nw.Int64())})+ )+ assert result == [{"list": [1, 2, 3, 4]}, {"list": [7, 8]}]+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_various_datatypes():+ data = [+ {+ "int": 1,+ "float": 1.5,+ "str": "hello",+ "bool": True,+ "datetime": datetime.datetime(2023, 1, 1, 12, 0),+ "date": datetime.date(2023, 1, 1),+ "duration": datetime.timedelta(days=1, hours=2, minutes=30),+ "list": [1, 2, 3],+ },+ {+ "int": 2,+ "float": 2.5,+ "str": "world",+ "bool": False,+ "datetime": datetime.datetime(2023, 2, 1, 12, 0),+ "date": datetime.date(2023, 2, 1),+ "duration": datetime.timedelta(days=2, hours=4, minutes=45),+ "list": [4, 5, 6],+ },+ ]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "int", "value": "3"},+ {"rowIdx": 0, "columnId": "float", "value": "3.14"},+ {"rowIdx": 0, "columnId": "str", "value": "updated"},+ {"rowIdx": 0, "columnId": "bool", "value": False},+ {+ "rowIdx": 0,+ "columnId": "datetime",+ "value": "2023-03-15T15:30:00",+ },+ {"rowIdx": 0, "columnId": "date", "value": "2023-03-15"},+ {"rowIdx": 0, "columnId": "duration", "value": "186300000000"},+ {"rowIdx": 0, "columnId": "list", "value": "[7, 8, 9]"},+ {"rowIdx": 1, "columnId": "int", "value": "4"},+ {"rowIdx": 1, "columnId": "float", "value": "4.5"},+ {"rowIdx": 1, "columnId": "str", "value": "updated2"},+ {"rowIdx": 1, "columnId": "bool", "value": True},+ {+ "rowIdx": 1,+ "columnId": "datetime",+ "value": "2023-04-20T10:00:00",+ },+ {"rowIdx": 1, "columnId": "date", "value": "2023-04-20"},+ {"rowIdx": 1, "columnId": "duration", "value": 186300000000},+ {"rowIdx": 1, "columnId": "list", "value": "10,11,12"},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [+ {+ "int": 3,+ "float": 3.14,+ "str": "updated",+ "bool": False,+ "datetime": datetime.datetime(2023, 1, 1, 12, 0),+ "date": datetime.date(2023, 3, 15),+ "duration": datetime.timedelta(days=2, seconds=13500),+ "list": [7, 8, 9],+ },+ {+ "int": 4,+ "float": 4.5,+ "str": "updated2",+ "bool": True,+ "datetime": datetime.datetime(2023, 1, 1, 12, 0),+ "date": datetime.date(2023, 4, 20),+ "duration": datetime.timedelta(days=2, seconds=13500),+ "list": [10, 11, 12],+ },+ ]++ # Test with explicit dtypes+ dtypes = nw.Schema(+ {+ "int": nw.Int64(),+ "float": nw.Float64(),+ "str": nw.String(),+ "bool": nw.Boolean(),+ "datetime": nw.Datetime(),+ "date": nw.Date(),+ "duration": nw.Duration(),+ "list": nw.List(nw.Int64()),+ }+ )+ result_with_dtypes = apply_edits(data, edits, schema=dtypes)+ assert result_with_dtypes == result+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_apply_edits_edge_cases():+ data = [+ {+ "empty_to_value": None,+ "value_to_empty": "hello",+ "zero_length_list": [],+ },+ {+ "empty_to_value": None,+ "value_to_empty": "world",+ "zero_length_list": [],+ },+ ]+ edits = {+ "edits": [+ {"rowIdx": 0, "columnId": "empty_to_value", "value": "filled"},+ {"rowIdx": 1, "columnId": "value_to_empty", "value": ""},+ {"rowIdx": 0, "columnId": "zero_length_list", "value": "[1]"},+ {"rowIdx": 1, "columnId": "zero_length_list", "value": "[]"},+ ]+ }+ result = apply_edits(data, edits)+ assert result == [+ {+ "empty_to_value": "filled",+ "value_to_empty": "hello",+ "zero_length_list": [1],+ },+ {"empty_to_value": None, "value_to_empty": "", "zero_length_list": []},+ ]++@pytest.mark.skipif(not DependencyManager.pandas.has(), reason="Pandas not installed")