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: don't convert classes that extend tuple/dict/list to structure when formatting (#3047)
Myles Scolnick3cd30114b2f3
diff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsxindex 44467320a2..2e6bc3924f 100644--- a/frontend/src/components/editor/output/JsonOutput.tsx+++ b/frontend/src/components/editor/output/JsonOutput.tsx@@ -48,6 +48,7 @@ export const JsonOutput: React.FC<Props> = memo(className="marimo-json-output"rootName={name}theme={theme}+ displayDataTypes={false}value={data}style={{backgroundColor: "transparent",@@ -101,6 +102,7 @@ const LEAF_RENDERERS = {"image/": (value: string) => <ImageOutput src={value} />,"video/": (value: string) => <VideoOutput src={value} />,"text/html": (value: string) => <HtmlOutput html={value} inline={true} />,+ "text/plain+float:": (value: string) => <span>{value}</span>,"text/plain": (value: string) => <CollapsibleTextOutput text={value} />,};diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.pyindex 1404dded87..e1bbf55dba 100644--- a/marimo/_output/formatters/structures.py+++ b/marimo/_output/formatters/structures.py@@ -9,24 +9,31 @@ from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output import formattingfrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.formatters.repr_formatters import maybe_get_repr_formatter+from marimo._plugins.stateless import plain_textfrom marimo._utils.flatten import CyclicStructureError, flatten-def _leaf_formatter(value: object) -> bool | None | str:+def _leaf_formatter(value: object) -> bool | None | str | int:formatter = formatting.get_formatter(value)if formatter is not None:return ":".join(formatter(value))if isinstance(value, bool):return value- elif value is None:+ if isinstance(value, str):+ return value+ if isinstance(value, int):+ return value+ # floats are still converted to strings because JavaScript+ # can't reliably distinguish between them (eg 1 and 1.0)+ if isinstance(value, float):+ return f"text/plain+float:{value}"+ if value is None:return value- else:- # floats and ints are still converted to strings because JavaScript- # can't reliably distinguish between them (eg 1 and 1.0)- try:- return f"text/plain:{json.dumps(value)}"- except TypeError:- return f"text/plain:{value}"++ try:+ return f"text/plain:{json.dumps(value)}"+ except TypeError:+ return f"text/plain:{value}"def format_structure(@@ -59,6 +66,19 @@ class StructuresFormatter(FormatterFactory):if repr_formatter is not None:return repr_formatter(t)+ # Check if the object is a subclass of tuple, list, or dict+ # and the repr is different from the default+ # e.g. sys.version_info+ if isinstance(t, tuple) and type(t) is not tuple:+ if str(t) != str(tuple(t)):+ return plain_text.plain_text(str(t))._mime_()+ elif isinstance(t, list) and type(t) is not list:+ if str(t) != str(list(t)):+ return plain_text.plain_text(str(t))._mime_()+ elif isinstance(t, dict) and type(t) is not dict:+ if str(t) != str(dict(t)):+ return plain_text.plain_text(str(t))._mime_()+if t and "matplotlib" in sys.modules:# Special case for matplotlib:#diff --git a/marimo/_smoke_tests/structures.py b/marimo/_smoke_tests/structures.pynew file mode 100644index 0000000000..c269d21ac2--- /dev/null+++ b/marimo/_smoke_tests/structures.py@@ -0,0 +1,86 @@+import marimo++__generated_with = "0.9.29"+app = marimo.App(width="medium")+++def __():+ [+ {+ "a": 1,+ "b": 2.0,+ "c": "foo",+ "d": True,+ "e": False,+ }+ ]+ return+++def __():+ class CustomList(list):+ def __init__(self, extra_arg):+ super().__init__((1, 2))+++ CustomList(1)+ return (CustomList,)+++def __():+ import marimo as mo+ return (mo,)+++def __():+ import sys++ # Even though this extends tuple, we preserve the repr+ sys.version_info+ return (sys,)+++def __(sys):+ repr(sys.version_info)+ return+++def __(sys):+ # Nested, so it is not preserved+ (sys.version_info,)+ return+++def __(sys):+ {1, 2, 3, sys.version_info}+ return+++def __():+ (1, 2, 3)+ return+++def __(mo):+ mo.refs()+ return+++def __(mo):+ x = 1+ mo.defs()+ return (x,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_islands/snapshots/island-mimetypes.txt b/tests/_islands/snapshots/island-mimetypes.txtindex 6658ef58cb..9198403681 100644--- a/tests/_islands/snapshots/island-mimetypes.txt+++ b/tests/_islands/snapshots/island-mimetypes.txt@@ -24,7 +24,7 @@data-reactive="true"><marimo-cell-output>- <marimo-json-output data-json-data='{"key": "text/plain:\"value\""}'></marimo-json-output>+ <marimo-json-output data-json-data='{"key": "value"}'></marimo-json-output></marimo-cell-output><marimo-cell-code hidden>%7B'key'%3A%20'value'%7D</marimo-cell-code></marimo-island>@@ -34,7 +34,7 @@data-reactive="true"><marimo-cell-output>- <marimo-json-output data-json-data='["text/plain:1", "text/html:<span class=\"markdown prose dark:prose-invert\"><span class=\"paragraph\">Hello</span></span>"]'></marimo-json-output>+ <marimo-json-output data-json-data='[1, "text/html:<span class=\"markdown prose dark:prose-invert\"><span class=\"paragraph\">Hello</span></span>"]'></marimo-json-output></marimo-cell-output><marimo-cell-code hidden>%5B1%2C%20mo.md('Hello')%5D</marimo-cell-code></marimo-island>\ No newline at end of filediff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex 53d30f1e7c..c1a449c74f 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -50,13 +50,13 @@ def test_formatters_with_opinionated_formatter() -> None:obj = ["test"]formatter = get_formatter(obj)assert formatter is not None- assert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')+ assert formatter(obj) == ("application/json", '["test"]')# With Plainobj = Plain(["test"])formatter = get_formatter(obj)assert formatter is not None- assert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')+ assert formatter(obj) == ("application/json", '["test"]')# With pandas DataFrameformatter = get_formatter(pd_df)diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.pyindex 6e2aff6559..56a6e1f705 100644--- a/tests/_output/formatters/test_structures.py+++ b/tests/_output/formatters/test_structures.py@@ -1,13 +1,26 @@from __future__ import annotations+import sysfrom typing import Any, List, castfrom marimo._dependencies.dependencies import DependencyManager-from marimo._output.formatters.structures import format_structure+from marimo._output.formatters.structures import (+ StructuresFormatter,+ format_structure,+)+from marimo._output.formatting import get_formatter+from marimo._output.md import md+from marimo._plugins.ui._impl.input import sliderfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider+def get_and_format(obj: Any) -> Any:+ formatter = get_formatter(obj)+ assert formatter is not None+ return formatter(obj)++async def test_matplotlib_special_case(executing_kernel: Kernel, exec_req: ExecReqProvider) -> None:@@ -42,9 +55,166 @@ def test_format_structure_types() -> None:formatted = cast(List[Any], format_structure(["hello", True, False, None, 1, 1.0]))- assert formatted[0] == 'text/plain:"hello"'+ assert formatted[0] == "hello"assert formatted[1] is Trueassert formatted[2] is Falseassert formatted[3] is None- assert formatted[4] == "text/plain:1"- assert formatted[5] == "text/plain:1.0"+ assert formatted[4] == 1+ assert formatted[5] == "text/plain+float:1.0"+++def test_format_structure_simple() -> None:+ StructuresFormatter().register()++ assert get_and_format([1, 2, 3, True, False, 1.0, 2.5]) == (+ "application/json",+ '[1, 2, 3, true, false, "text/plain+float:1.0", "text/plain+float:2.5"]',+ )+ assert get_and_format((1, 2, 3, True, False, 1.0, 2.5)) == (+ "application/json",+ '[1, 2, 3, true, false, "text/plain+float:1.0", "text/plain+float:2.5"]',+ )+ assert get_and_format(+ {"a": 1, "b": 2, "c": 3, "d": True, "e": False, "f": 1.0, "g": 2.5}+ ) == (+ "application/json",+ '{"a": 1, "b": 2, "c": 3, "d": true, "e": false, "f": "text/plain+float:1.0", "g": "text/plain+float:2.5"}',+ )+++def test_format_structure_nested() -> None:+ StructuresFormatter().register()++ nested_structure = {+ "a": [1, 2, {"b": 3, "c": True}],+ "d": (4, 5, False, 1.0),+ }+ assert get_and_format(nested_structure) == (+ "application/json",+ '{"a": [1, 2, {"b": 3, "c": true}], "d": [4, 5, false, "text/plain+float:1.0"]}',+ )+++def test_format_structure_nested_with_html() -> None:+ StructuresFormatter().register()++ _markdown = md("# hello")+ _slider = slider(start=0, stop=100)+ nested_structure = [1, _markdown, _slider]++ def escape(s: str) -> str:+ return s.replace('"', '\\"')++ assert get_and_format(nested_structure) == (+ "application/json",+ f'[1, "text/html:{escape(_markdown.text)}", "text/html:{escape(_slider.text)}"]',+ )+++def test_format_structure_cyclic() -> None:+ StructuresFormatter().register()++ cyclic_structure = []+ cyclic_structure.append(cyclic_structure)++ assert get_and_format(cyclic_structure) == (+ "text/plain",+ "[[...]]",+ )+++def test_format_structure_subclasses_no_repr() -> None:+ StructuresFormatter().register()++ class CustomList(list):+ pass++ custom_list = CustomList([1, 2, 3])+ assert get_and_format(custom_list) == ("application/json", "[1, 2, 3]")++ class CustomDict(dict):+ pass++ custom_dict = CustomDict({"a": 1, "b": 2, "c": 3})+ assert get_and_format(custom_dict) == (+ "application/json",+ '{"a": 1, "b": 2, "c": 3}',+ )++ class CustomTuple(tuple):+ pass++ custom_tuple = CustomTuple((1, 2, 3))+ assert get_and_format(custom_tuple) == ("application/json", "[1, 2, 3]")+++def test_format_structure_subclasses_with_repr_html() -> None:+ StructuresFormatter().register()++ class CustomList(list):+ def _repr_html_(self) -> str:+ return "<b>CustomList</b>"++ custom_list = CustomList([1, 2, 3])+ assert get_and_format(custom_list) == ("text/html", "<b>CustomList</b>")++ class CustomDict(dict):+ def _repr_html_(self) -> str:+ return "<b>CustomDict</b>"++ custom_dict = CustomDict({"a": 1, "b": 2, "c": 3})+ assert get_and_format(custom_dict) == ("text/html", "<b>CustomDict</b>")++ class CustomTuple(tuple):+ def _repr_html_(self) -> str:+ return "<b>CustomTuple</b>"++ custom_tuple = CustomTuple((1, 2, 3))+ assert get_and_format(custom_tuple) == ("text/html", "<b>CustomTuple</b>")+++def test_format_structure_subclasses_with_different_built_in_repr() -> None:+ StructuresFormatter().register()++ class CustomList(list):+ def __init__(self) -> None:+ super().__init__((1, 2, 3))++ def __repr__(self) -> str:+ return "CustomList(a=1, b=2, c=3)"++ custom_list = CustomList()+ assert get_and_format(custom_list) == (+ "text/html",+ "<pre style='font-size: 12px'>CustomList(a=1, b=2, c=3)</pre>",+ )++ class CustomDict(dict):+ def __init__(self) -> None:+ super().__init__({"a": 1, "b": 2, "c": 3})++ def __repr__(self) -> str:+ return "CustomDict(a=1, b=2, c=3)"++ custom_dict = CustomDict()+ assert get_and_format(custom_dict) == (+ "text/html",+ "<pre style='font-size: 12px'>CustomDict(a=1, b=2, c=3)</pre>",+ )++ class CustomTuple(tuple):+ def __init__(self) -> None:+ super().__init__()++ def __repr__(self) -> str:+ return "CustomTuple(a=1, b=2, c=3)"++ custom_tuple = CustomTuple()+ assert get_and_format(custom_tuple) == (+ "text/html",+ "<pre style='font-size: 12px'>CustomTuple(a=1, b=2, c=3)</pre>",+ )++ assert get_and_format(sys.version_info)[1].startswith(+ "<pre style='font-size: 12px'>sys.version_info(major=3"+ )