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: explicit field types for mo.ui.dataframe (#1144)
Myles Scolnick8c64be03757f
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxindex e8027b8604..f3cf5182b7 100644--- a/frontend/src/components/editor/file-tree/file-explorer.tsx+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -187,7 +187,7 @@ const Toolbar = ({ onRefresh }: { onRefresh: () => void }) => {const Show = ({ node }: { node: NodeApi<FileInfo> }) => {return (<span- className="flex-1"+ className="flex-1 overflow-hidden text-ellipsis"onClick={(e) => {if (node.data.isDirectory) {return;@@ -293,13 +293,13 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {<FolderArrow node={node} /><spanclassName={cn(- "flex items-center gap-2 px-1 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1",+ "flex items-center pl-1 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1 overflow-hidden",node.willReceiveDrop &&node.data.isDirectory &&"bg-accent/80 hover:bg-accent/80 text-accent-foreground",)}>- <Icon className="w-5 h-5 flex-shrink-0" strokeWidth={1.5} />+ <Icon className="w-5 h-5 flex-shrink-0 mr-2" strokeWidth={1.5} />{node.isEditing ? <Edit node={node} /> : <Show node={node} />}<DropdownMenu modal={false}><DropdownMenuTriggerdiff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.tsindex 92fb1de4e3..da75e2270d 100644--- a/frontend/src/core/pyodide/worker/types.ts+++ b/frontend/src/core/pyodide/worker/types.ts@@ -38,7 +38,7 @@ export interface WasmController {queryParameters: Record<string, string | string[]>;code: string;filename: string | null;- userConfig: UserConfig | null;+ userConfig: UserConfig;onMessage: (message: JsonString<OperationMessage>) => void;}): Promise<SerializedBridge>;}diff --git a/frontend/src/core/pyodide/worker/worker.ts b/frontend/src/core/pyodide/worker/worker.tsindex 1e703a5114..575adf89a1 100644--- a/frontend/src/core/pyodide/worker/worker.ts+++ b/frontend/src/core/pyodide/worker/worker.ts@@ -76,7 +76,7 @@ const requestHandler = createRPCRequestHandler({queryParameters: Record<string, string | string[]>;code: string;filename: string | null;- userConfig: UserConfig | null;+ userConfig: UserConfig;}) => {await pyodideReadyPromise; // Make sure loading is donediff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 844c71f669..d127a0f8ea 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -12,6 +12,8 @@ import { Alert, AlertTitle } from "@/components/ui/alert";import { rpc } from "../core/rpc";import { createPlugin } from "../core/builder";import { vegaLoadData } from "./vega/loader";+import { VegaType } from "./vega/vega-loader";+import { getVegaFieldTypes } from "./vega/utils";/*** Arguments for a data table@@ -27,6 +29,7 @@ interface Data<T> {selection: "single" | "multi" | null;showDownload: boolean;rowHeaders: Array<[string, string[]]>;+ fieldTypes?: Record<string, VegaType> | null;}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions@@ -47,6 +50,11 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")selection: z.enum(["single", "multi"]).nullable().default(null),showDownload: z.boolean().default(false),rowHeaders: z.array(z.tuple([z.string(), z.array(z.any())])),+ fieldTypes: z+ .record(+ z.enum(["boolean", "integer", "number", "date", "string", "unknown"]),+ )+ .nullish(),}),).withFunctions<Functions>({@@ -90,8 +98,12 @@ export const LoadingDataTableComponent = (if (!props.data) {return Promise.resolve([]);}- return vegaLoadData(props.data, { type: "csv", parse: "auto" }, true);- }, [props.data]);+ return vegaLoadData(+ props.data,+ { type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },+ true,+ );+ }, [props.data, props.fieldTypes]);if (loading && !data) {return null;diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.tsindex b4180b1e75..f60c5ee34b 100644--- a/frontend/src/plugins/impl/vega/loader.ts+++ b/frontend/src/plugins/impl/vega/loader.ts@@ -1,17 +1,26 @@/* Copyright 2024 Marimo. All rights reserved. */-// @ts-expect-error - no types-import { loader as createLoader, read, typeParsers } from "vega-loader";import { DataFormat } from "./types";import { isNumber } from "lodash-es";+import { typeParsers, createLoader, read, FieldTypes } from "./vega-loader";// Augment the typeParsers to support DatetypeParsers.date = (value: string) => new Date(value).toISOString();+const previousNumberParser = typeParsers.number;const previousIntegerParser = typeParsers.integer;-// We need to use BigInt for numbers to support large numbers-const bigIntIntegerParser = (v: string) => {++// Custom parser to:+// - handle BigInt+// - handle inf and -inf+const customIntegerParser = (v: string) => {if (v === "") {return "";}+ if (v === "-inf") {+ return v;+ }+ if (v === "inf") {+ return v;+ }if (isNumber(Number.parseInt(v))) {try {@@ -26,12 +35,26 @@ const bigIntIntegerParser = (v: string) => {}};+// Custom number parser to:+// - handle inf and -inf+const customNumberParser = (v: string) => {+ if (v === "-inf") {+ return v;+ }+ if (v === "inf") {+ return v;+ }+ return previousNumberParser(v);+};+function enableBigInt() {- typeParsers.integer = bigIntIntegerParser;+ typeParsers.integer = customIntegerParser;+ typeParsers.number = customNumberParser;}function disableBigInt() {typeParsers.integer = previousIntegerParser;+ typeParsers.number = previousNumberParser;}export const vegaLoader = createLoader();@@ -46,7 +69,7 @@ export function vegaLoadData(format: DataFormat | undefined | { type: "csv"; parse: "auto" },handleBigInt = false,): Promise<object[]> {- return vegaLoader.load(url).then((csvData: string) => {+ return vegaLoader.load(url).then((csvData) => {// CSV data comes columnar and may have duplicate column names.// We need to uniquify the column names before parsing since vega-loader// returns an array of objects which drops duplicate keys.@@ -68,7 +91,10 @@ export function vegaLoadData(const results =format && format.type === "csv"? // csv -> json- read(csvData, { ...format, parse: "auto" })+ read(csvData, {+ ...format,+ parse: (format.parse as FieldTypes) || "auto",+ }): read(csvData, format);if (handleBigInt) {diff --git a/frontend/src/plugins/impl/vega/utils.ts b/frontend/src/plugins/impl/vega/utils.tsindex 171d7aeff5..f214d942f2 100644--- a/frontend/src/plugins/impl/vega/utils.ts+++ b/frontend/src/plugins/impl/vega/utils.ts@@ -1,4 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */++import { Objects } from "@/utils/objects";+import { FieldTypes } from "./vega-loader";+export function mergeAsArrays<T>(left: T | T[] | undefined,right: T | T[] | undefined,@@ -15,3 +19,22 @@ function toArray<T>(value: T | T[] | undefined): T[] {}return [value];}++export function getVegaFieldTypes(+ types: FieldTypes | undefined | null,+): FieldTypes | "auto" {+ if (!types || Object.keys(types).length === 0) {+ // If fieldTypes is provided, use it to parse the data+ // Otherwise, infer the data types+ return "auto";+ }+ // Convert all 'data' to 'string', because dates don't format back to+ // the correct formatting. For example, a date like '2024-01-01' will+ // be formatted to '2024-01-01T00:00:00.000Z'.+ return Objects.mapValues(types, (type) => {+ if (type === "date") {+ return "string";+ }+ return type;+ });+}diff --git a/frontend/src/plugins/impl/vega/vega-loader.ts b/frontend/src/plugins/impl/vega/vega-loader.tsnew file mode 100644index 0000000000..064a96569c--- /dev/null+++ b/frontend/src/plugins/impl/vega/vega-loader.ts@@ -0,0 +1,47 @@+/* Copyright 2024 Marimo. All rights reserved. */+// @ts-expect-error - no types+import * as vl from "vega-loader";+import { DataFormat } from "./types";++// Re-export the vega-loader functions to add TypeScript types++export function read(+ data: string | Record<string, unknown> | Array<Record<string, unknown>>,+ format:+ | DataFormat+ | {+ type: DataFormat["type"];+ parse: "auto";+ }+ | {+ type: DataFormat["type"];+ parse: FieldTypes;+ }+ | undefined,+): object[] {+ return vl.read(data, format);+}++export function createLoader(): {+ load: (+ url: string,+ ) => Promise<+ string | Record<string, unknown> | Array<Record<string, unknown>>+ >;+ http: (url: string) => Promise<string>;+} {+ return vl.loader();+}++export type VegaType =+ | "boolean"+ | "integer"+ | "number"+ | "date"+ | "string"+ | "unknown";++export type FieldTypes = Record<string, VegaType>;++export const typeParsers: Record<VegaType, (value: string) => unknown> =+ vl.typeParsers;diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.pyindex d573437f24..13999a02a4 100644--- a/marimo/_plugins/core/json_encoder.py+++ b/marimo/_plugins/core/json_encoder.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import jsonfrom json import JSONEncoderfrom typing import Any@@ -24,7 +26,7 @@ class WebComponentEncoder(JSONEncoder):elif isinstance(obj, np.ndarray):if any([np.issubdtype(obj.dtype, i) for i in dtypes]):return obj.astype(str).tolist()- return obj.tolist()+ return str(obj.tolist())elif isinstance(obj, np.dtype):return str(obj)@@ -39,10 +41,16 @@ class WebComponentEncoder(JSONEncoder):return obj.to_list()elif isinstance(obj, pd.Categorical):return obj.tolist()+ elif isinstance(obj, pd.CategoricalDtype):+ return str(obj)elif isinstance(obj, pd.Timestamp):return str(obj)+ elif isinstance(obj, pd.Timedelta):+ return str(obj)elif isinstance(obj, pd.Interval):return str(obj)+ elif isinstance(obj, pd.TimedeltaIndex):+ return str(obj.astype(str).tolist())# Catch-all for other pandas objectstry:@@ -60,5 +68,9 @@ class WebComponentEncoder(JSONEncoder):if isinstance(obj, bytes):return obj.decode("utf-8")+ # Handle set+ if isinstance(obj, set):+ return list(obj)+# Fallthrough to default encoderreturn JSONEncoder.default(self, obj)diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex a2ae90aea1..52d3165706 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -5,6 +5,7 @@ import inspectimport sysfrom typing import TYPE_CHECKING, Any, Callable, Dict, Final, List, Optional+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.dataframes.handlers import TransformsContainerfrom marimo._plugins.ui._impl.dataframes.transforms import Transformationsfrom marimo._plugins.ui._impl.tables.pandas_table import (@@ -90,6 +91,14 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):df: pd.DataFrame,on_change: Optional[Callable[[pd.DataFrame], None]] = None,) -> None:+ DependencyManager.require_pandas("to use the dataframe plugin")+ import pandas as pd++ if not isinstance(df, pd.DataFrame):+ raise ValueError(+ "Dataframe plugin only supports Pandas DataFrames"+ )+# HACK: this is a hack to get the name of the variable that was passeddataframe_name = "df"try:diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 13d9a197b9..6f188b69f6 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -21,7 +21,9 @@ from marimo._output.mime import MIMEfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElement-from marimo._plugins.ui._impl.tables.table_manager import TableManager+from marimo._plugins.ui._impl.tables.table_manager import (+ TableManager,+)from marimo._plugins.ui._impl.tables.utils import get_table_managerfrom marimo._plugins.ui._impl.utils.dataframe import ListOrTuple, TableDatafrom marimo._runtime.functions import Function@@ -164,6 +166,7 @@ class table(can_download = (DependencyManager.has_pandas() or DependencyManager.has_polars())+ field_types = self._manager.get_field_types()super().__init__(component_name=table._name,@@ -173,6 +176,7 @@ class table("data": self._manager.to_data(),"pagination": pagination,"page-size": page_size,+ "field-types": field_types if field_types else None,"selection": selection,"show-download": can_download,"row-headers": self._manager.get_row_headers(),diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 3c5f13493d..2c576fbbd6 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom typing import Anyfrom marimo._plugins.ui._impl.tables.table_manager import (+ FieldType,+ FieldTypes,TableManager,TableManagerFactory,)@@ -77,4 +79,35 @@ class PandasTableManagerFactory(TableManagerFactory):return []+ def get_field_types(self) -> FieldTypes:+ return {+ column: PandasTableManager._get_field_type(+ self.data[column]+ )+ for column in self.data.columns+ }++ @staticmethod+ def _get_field_type(series: pd.Series[Any]) -> FieldType:+ dtype = str(series.dtype)+ if dtype.startswith("interval"):+ return "string"+ if dtype.startswith("int") or dtype.startswith("uint"):+ return "integer"+ if dtype.startswith("float"):+ return "number"+ if dtype == "object":+ return "string"+ if dtype == "bool":+ return "boolean"+ if dtype == "datetime64[ns]":+ return "date"+ if dtype == "timedelta64[ns]":+ return "string"+ if dtype == "category":+ return "string"+ if dtype.startswith("complex"):+ return "unknown"+ return "unknown"+return PandasTableManagerdiff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 4426d5d296..35d52d45cb 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom typing import Anyfrom marimo._plugins.ui._impl.tables.table_manager import (+ FieldType,+ FieldTypes,TableManager,TableManagerFactory,)@@ -39,4 +41,27 @@ class PolarsTableManagerFactory(TableManagerFactory):def is_type(value: Any) -> bool:return isinstance(value, pl.DataFrame)+ def get_field_types(self) -> FieldTypes:+ return {+ column: PolarsTableManager._get_field_type(+ self.data[column]+ )+ for column in self.data.columns+ }++ @staticmethod+ def _get_field_type(column: pl.Series) -> FieldType:+ if column.is_utf8():+ return "string"+ elif column.is_boolean():+ return "boolean"+ elif column.is_integer():+ return "integer"+ elif column.is_float() or column.is_numeric():+ return "number"+ elif column.is_temporal():+ return "date"+ else:+ return "unknown"+return PolarsTableManagerdiff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.pyindex cd47fce3fd..f99581870f 100644--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py@@ -2,9 +2,11 @@from __future__ import annotationsimport io-from typing import Any, Union+from typing import Any, Union, castfrom marimo._plugins.ui._impl.tables.table_manager import (+ FieldType,+ FieldTypes,TableManager,TableManagerFactory,)@@ -57,4 +59,33 @@ class PyArrowTableManagerFactory(TableManagerFactory):value, pa.RecordBatch)+ def get_field_types(self) -> FieldTypes:+ return {+ column: PyArrowTableManager._get_field_type(+ cast(Any, self.data)[idx]+ )+ for idx, column in enumerate(self.data.schema.names)+ }++ @staticmethod+ def _get_field_type(column: pa.Array[Any, Any]) -> FieldType:+ if isinstance(column, pa.NullArray):+ return "unknown"+ elif pa.types.is_string(column.type):+ return "string"+ elif pa.types.is_boolean(column.type):+ return "boolean"+ elif pa.types.is_integer(column.type):+ return "integer"+ elif pa.types.is_floating(column.type) or pa.types.is_decimal(+ column.type+ ):+ return "number"+ elif pa.types.is_date(column.type) or pa.types.is_timestamp(+ column.type+ ):+ return "date"+ else:+ return "unknown"+return PyArrowTableManagerdiff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 79721ff47f..9d1d1dffdb 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -2,7 +2,7 @@from __future__ import annotationsimport abc-from typing import Any, Generic, TypeVar+from typing import Any, Dict, Generic, Literal, TypeVarimport marimo._output.data.data as mo_datafrom marimo._plugins.core.web_component import JSONType@@ -10,6 +10,13 @@ from marimo._plugins.core.web_component import JSONTypeT = TypeVar("T")+# This is the frontend type for how the frontend should parse the data+FieldType = Literal[+ "string", "boolean", "integer", "number", "date", "unknown"+]+FieldTypes = Dict[str, FieldType]++class TableManager(abc.ABC, Generic[T]):def __init__(self, data: T) -> None:self.data = data@@ -39,6 +46,11 @@ class TableManager(abc.ABC, Generic[T]):def get_row_headers(self) -> list[tuple[str, list[str | int | float]]]:raise NotImplementedError+ def get_field_types(self) -> FieldTypes:+ # By default, don't provide any field types+ # so the frontend can infer them+ return {}+@staticmethod@abc.abstractmethoddef is_type(value: Any) -> bool:diff --git a/marimo/_smoke_tests/bugs/1140.py b/marimo/_smoke_tests/bugs/1140.pynew file mode 100644index 0000000000..cf03268a8f--- /dev/null+++ b/marimo/_smoke_tests/bugs/1140.py@@ -0,0 +1,144 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.4.3"+app = marimo.App(width="full")+++def __():+ import pandas as pd+ import numpy as np+ import marimo as mo+ return mo, np, pd+++def __(mo):+ mo.md("""+ This highlights some of the differences between displaying data in different libraries: polars, pandas, pyarrow, and dictionaries.++ These differences are due to how each library prints their data as CSVs.+ """)+ return+++def __(np, pd):+ data = {+ 'Integer': [1, 2, 3],+ 'Float': [1.0, 2.5, 3.5],+ 'String': ['apple', 'banana', 'cherry'],+ 'Boolean': [True, False, True],+ 'LargeInt': np.array([1e12, 2e12, 3e12], dtype=np.int64),+ 'LargeFloat': np.array([1.234567890123456789, 2.234567890123456789, 3.234567890123456789], dtype=np.float64),+ 'DateTime': pd.to_datetime(['2021-01-01', '2021-06-01', '2021-09-01']),+ 'Timedelta': pd.to_timedelta(['1 days', '2 days', '3 days']),+ 'Categorical': pd.Categorical(['test', 'train', 'test']),+ 'NumpyArray': [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])],+ 'Duration': pd.to_timedelta(['10:00:00', '15:30:00', '20:45:00']),+ 'Series': [pd.Series([1, 2, 3]), pd.Series([1, 2, 3]), pd.Series([1, 2, 3])],+ 'Nested': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}],+ 'Mixed': [1, 1.1, '1'],+ 'Mixed 2': [True, np.array([1, 2, 3]), pd.to_datetime('2021-01-01')],+ 'Null': [None, None, None],+ 'NaN': [np.nan, np.nan, np.nan],+ 'Infinity': [np.inf, np.inf, np.inf],+ 'Negative Infinity': [-np.inf, -np.inf, -np.inf],+ 'Zero': [0, 0, 0],+ 'Empty': ['', '', ''],+ 'Empty List': [[], [], []],+ 'Empty Dict': [{}, {}, {}],+ 'Set': [set(), set(["a", "b"]), set([1, 2])],+ 'Empty Tuple': [(), (), ()],+ }+ return data,+++def __(df, mo):+ mo.ui.table(df, label="Pandas")+ return+++def __(data, pd):+ df = pd.DataFrame(data)+ df+ return df,+++def __(df, mo):+ mo.ui.dataframe(df)+ return+++def __(df, mo):+ mo.ui.table(df.to_dict(orient='records'), label="List of dictionaries")+ return+++def __(data_2, mo, pd):+ # Arrow+ import pyarrow as pa+ import pyarrow.parquet as pq+ table = pa.Table.from_pandas(pd.DataFrame(data_2))+ mo.ui.table(table, label="Pyarrow")+ return pa, pq, table+++def __(np, pd):+ data_2 = {+ 'Integer': [1, 2, 3],+ 'Float': [1.0, 2.5, 3.5],+ 'String': ['apple', 'banana', 'cherry'],+ 'Boolean': [True, False, True],+ 'LargeInt': np.array([1e12, 2e12, 3e12], dtype=np.int64),+ 'LargeFloat': np.array([1.234567890123456789, 2.234567890123456789, 3.234567890123456789], dtype=np.float64),+ 'DateTime': pd.to_datetime(['2021-01-01', '2021-06-01', '2021-09-01']),+ # Not support in polars+ # 'Timedelta': pd.to_timedelta(['1 days', '2 days', '3 days']),+ # 'Categorical': pd.Categorical(['test', 'train', 'test']),+ # CSV does not support nested data+ # 'NumpyArray': [np.array([1, 2, 3]), np.array([4, 5, 6]), np.array([7, 8, 9])],+ # 'Nested': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}],+ # 'Duration': pd.to_timedelta(['10:00:00', '15:30:00', '20:45:00'])+ # 'Mixed': [1, 1.1, '1'],+ # Mixed 2 is not supported in polars+ # 'Mixed 2': [True, np.array([1, 2, 3]), pd.to_datetime('2021-01-01')],+ 'Null': [None, None, None],+ 'NaN': [np.nan, np.nan, np.nan],+ 'Infinity': [np.inf, np.inf, np.inf],+ 'Negative Infinity': [-np.inf, -np.inf, -np.inf],+ 'Zero': [0, 0, 0],+ 'Empty': ['', '', ''],+ # More nested not supported+ # 'Empty List': [[], [], []],+ # 'Empty Dict': [{}, {}, {}],+ # 'Empty Set': [set(), set(), set()],+ # 'Empty Tuple': [(), (), ()],+ }+ return data_2,+++def __(data_2, mo):+ # Polars+ import polars as pl+ pl_df = pl.DataFrame(data_2)+ mo.ui.table(pl_df, label="Polars")+ return pl, pl_df+++def __(pl_df):+ pl_df+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_cli/snapshots/script.txt b/tests/_cli/snapshots/script.txtindex bd0e2479fc..6525b9c1bb 100644--- a/tests/_cli/snapshots/script.txt+++ b/tests/_cli/snapshots/script.txt@@ -1,5 +1,5 @@-__generated_with = "0.4.3"+__generated_with = "0.0.0"import marimo as modiff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 97923c3ec3..9e75194f60 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -7,6 +7,7 @@ import subprocessfrom os import pathfrom typing import TYPE_CHECKING+from marimo import __version__from tests._server.templates.utils import normalize_index_htmlfrom tests.mocks import snapshotter@@ -225,7 +226,9 @@ class TestExportScript:capture_output=True,)assert p.returncode == 0, p.stderr.decode()- snapshot("script.txt", p.stdout.decode())+ output = p.stdout.decode()+ output = output.replace(__version__, "0.0.0")+ snapshot("script.txt", output)@staticmethoddef test_export_script_async(temp_async_marimo_file: str) -> None:diff --git a/tests/_plugins/core/test_json_encoder.py b/tests/_plugins/core/test_json_encoder.pyindex 81f7a08db5..bbc7d5de6f 100644--- a/tests/_plugins/core/test_json_encoder.py+++ b/tests/_plugins/core/test_json_encoder.py@@ -17,7 +17,7 @@ def test_numpy_encoding() -> None:arr = np.array([1, 2, 3])encoded = json.dumps(arr, cls=WebComponentEncoder)- assert encoded == "[1, 2, 3]"+ assert encoded == '"[1, 2, 3]"'dt64 = np.datetime64("2021-01-01T12:00:00")encoded_dt64 = json.dumps(dt64, cls=WebComponentEncoder)@@ -70,6 +70,20 @@ def test_pandas_encoding() -> None:encoded_interval = json.dumps(interval, cls=WebComponentEncoder)assert encoded_interval == '"(0, 5]"'+ # Timedelta+ timedelta = pd.Timedelta("1 days")+ encoded_timedelta = json.dumps(timedelta, cls=WebComponentEncoder)+ assert encoded_timedelta == '"1 days 00:00:00"'++ timedelta_arr = pd.to_timedelta(["1 days", "2 days", "3 days"])+ encoded_timedelta_arr = json.dumps(timedelta_arr, cls=WebComponentEncoder)+ assert encoded_timedelta_arr == "\"['1 days', '2 days', '3 days']\""++ # Catch-all+ other = pd.Series(["a", "b", "c"])+ encoded_other = json.dumps(other, cls=WebComponentEncoder)+ assert encoded_other == '["a", "b", "c"]'+class MockMIMEObject:def _mime_(self) -> tuple[str, str]:@@ -86,3 +100,51 @@ def test_bytes_encoding() -> None:bytes_obj = b"hello"encoded = json.dumps(bytes_obj, cls=WebComponentEncoder)assert encoded == '"hello"'+++def test_set_encoding() -> None:+ set_obj = set(["a", "b"])+ encoded = json.dumps(set_obj, cls=WebComponentEncoder)+ assert encoded == '["a", "b"]' or encoded == '["b", "a"]'+ empty_set = set()+ encoded_empty = json.dumps(empty_set, cls=WebComponentEncoder)+ assert encoded_empty == "[]"+ number_set = set([1, 2])+ encoded_number = json.dumps(number_set, cls=WebComponentEncoder)+ assert encoded_number == "[1, 2]" or encoded_number == "[2, 1]"+++def test_null_encoding() -> None:+ null = None+ encoded = json.dumps(null, cls=WebComponentEncoder)+ assert encoded == "null"+++def test_inf_encoding() -> None:+ inf = float("inf")+ encoded = json.dumps(inf, cls=WebComponentEncoder)+ assert encoded == "Infinity"+++def test_nan_encoding() -> None:+ nan = float("nan")+ encoded = json.dumps(nan, cls=WebComponentEncoder)+ assert encoded == "NaN"+++def test_empty_encoding() -> None:+ empty = ""+ encoded = json.dumps(empty, cls=WebComponentEncoder)+ assert encoded == '""'+ empty_list = []+ encoded_list = json.dumps(empty_list, cls=WebComponentEncoder)+ assert encoded_list == "[]"+ empty_dict = {}+ encoded_dict = json.dumps(empty_dict, cls=WebComponentEncoder)+ assert encoded_dict == "{}"+ empty_tuple = ()+ encoded_tuple = json.dumps(empty_tuple, cls=WebComponentEncoder)+ assert encoded_tuple == "[]"+ empty_nested = [[], [], []]+ encoded_nested = json.dumps(empty_nested, cls=WebComponentEncoder)+ assert encoded_nested == "[[], [], []]"diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex 68207d7ccb..db14c5c25d 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -1,3 +1,5 @@+from __future__ import annotations+import unittestfrom typing import Any, Dict@@ -63,3 +65,6 @@ class TestColumnarDefaultTable(unittest.TestCase):def test_is_type(self) -> None:assert self.manager.is_type(self.data)assert not self.manager.is_type("not a dataframe")++ def test_get_field_types(self) -> None:+ assert self.manager.get_field_types() == {}diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex a11fdb9624..0b08e5e9ff 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -1,3 +1,5 @@+from __future__ import annotations+import unittestimport pytest@@ -49,3 +51,55 @@ class TestPandasTableManager(unittest.TestCase):def test_is_type(self) -> None:assert self.manager.is_type(self.data)assert not self.manager.is_type("not a dataframe")++ def test_get_field_types(self) -> None:+ import pandas as pd++ expected_field_types = {+ "A": "integer",+ "B": "string",+ }+ assert self.manager.get_field_types() == expected_field_types++ complex_data = pd.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [1.0, 2.0, 3.0],+ "D": [True, False, True],+ "E": [1 + 2j, 3 + 4j, 5 + 6j],+ "F": [None, None, None],+ "G": [set([1, 2]), set([3, 4]), set([5, 6])],+ "H": [+ pd.Timestamp("2021-01-01"),+ pd.Timestamp("2021-01-02"),+ pd.Timestamp("2021-01-03"),+ ],+ "I": [+ pd.Timedelta("1 days"),+ pd.Timedelta("2 days"),+ pd.Timedelta("3 days"),+ ],+ "J": [+ pd.Interval(left=0, right=5),+ pd.Interval(left=5, right=10),+ pd.Interval(left=10, right=15),+ ],+ }+ )+ expected_field_types = {+ "A": "integer",+ "B": "string",+ "C": "number",+ "D": "boolean",+ "E": "unknown",+ "F": "string",+ "G": "string",+ "H": "date",+ "I": "string",+ "J": "string",+ }+ assert (+ self.factory.create()(complex_data).get_field_types()+ == expected_field_types+ )diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex 0d3733c9c5..d6ead0e469 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -1,3 +1,5 @@+from __future__ import annotations+import unittestimport pytest@@ -46,3 +48,55 @@ class TestPolarsTableManagerFactory(unittest.TestCase):def test_is_type(self) -> None:assert self.manager.is_type(self.data)assert not self.manager.is_type("not a dataframe")++ def test_get_field_types(self) -> None:+ import polars as pl++ expected_field_types = {+ "A": "integer",+ "B": "string",+ }+ assert self.manager.get_field_types() == expected_field_types++ complex_data = pl.DataFrame(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [1.0, 2.0, 3.0],+ "D": [True, False, True],+ "E": [1 + 2j, 3 + 4j, 5 + 6j],+ "F": [None, None, None],+ "G": [set([1, 2]), set([3, 4]), set([5, 6])],+ "H": [+ pl.Date(2021, 1, 1),+ pl.Date(2021, 1, 2),+ pl.Date(2021, 1, 3),+ ],+ "I": [+ pl.Time(0, 0, 0),+ pl.Time(1, 0, 0),+ pl.Time(2, 0, 0),+ ],+ "J": [+ pl.Duration("ms"),+ pl.Duration("ms"),+ pl.Duration("ms"),+ ],+ }+ )+ expected_field_types = {+ "A": "integer",+ "B": "string",+ "C": "number",+ "D": "boolean",+ "E": "unknown",+ "F": "number",+ "G": "unknown",+ "H": "unknown",+ "I": "unknown",+ "J": "unknown",+ }+ assert (+ self.factory.create()(complex_data).get_field_types()+ == expected_field_types+ )diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.pyindex 3675daaa39..9ef032fbd4 100644--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py@@ -1,3 +1,5 @@+from __future__ import annotations+import unittestimport pytest@@ -16,7 +18,7 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):import pyarrow as paself.factory = PyArrowTableManagerFactory()- self.data = pa.table({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ self.data = pa.table({"A": [1, 2, 3], "B": ["a", "b", "c"]}) # type: ignoreself.manager = self.factory.create()(self.data)def test_package_name(self) -> None:@@ -45,3 +47,33 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):def test_is_type(self) -> None:assert self.manager.is_type(self.data)assert not self.manager.is_type("not a dataframe")++ def test_get_field_types(self) -> None:+ import pyarrow as pa++ expected_field_types = {+ "A": "integer",+ "B": "string",+ }+ assert self.manager.get_field_types() == expected_field_types++ complex_data = pa.table(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [1.0, 2.0, 3.0],+ "D": [True, False, True],+ "E": [None, None, None],+ } # type: ignore+ )+ expected_field_types = {+ "A": "integer",+ "B": "string",+ "C": "number",+ "D": "boolean",+ "E": "unknown",+ }+ assert (+ self.factory.create()(complex_data).get_field_types()+ == expected_field_types+ )