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: prefer _repr_ methods on list/dicts/tuple (#2842)
Myles Scolnick28d3d747b839
diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.pynew file mode 100644index 0000000000..e76b389d29--- /dev/null+++ b/marimo/_output/formatters/repr_formatters.py@@ -0,0 +1,87 @@+from __future__ import annotations++from typing import Any, Callable, Optional, Tuple++from marimo._messaging.mimetypes import KnownMimeType+from marimo._plugins.core.media import io_to_data_url+from marimo._utils.methods import is_callable_method+++def maybe_get_repr_formatter(+ obj: Any,+) -> Optional[Callable[[Any], tuple[KnownMimeType, str]]]:+ """+ Get a formatter that uses the object's _repr_ methods.+ """+ md_mime_types: list[KnownMimeType] = [+ "text/markdown",+ "text/latex",+ ]++ # Check for the misc _repr_ methods+ # Order dictates preference+ reprs: list[Tuple[str, KnownMimeType]] = [+ ("_repr_html_", "text/html"), # text/html is preferred first+ ("_repr_mimebundle_", "application/vnd.marimo+mimebundle"),+ ("_repr_svg_", "image/svg+xml"),+ ("_repr_json_", "application/json"),+ ("_repr_png_", "image/png"),+ ("_repr_jpeg_", "image/jpeg"),+ ("_repr_markdown_", "text/markdown"),+ ("_repr_latex_", "text/latex"),+ ("_repr_text_", "text/plain"), # last+ ]+ has_possible_repr = any(is_callable_method(obj, attr) for attr, _ in reprs)+ if has_possible_repr:+ # If there is any match, we return a formatter that calls+ # all the possible _repr_ methods, since some can be implemented+ # but return None+ def f_repr(obj: Any) -> tuple[KnownMimeType, str]:+ for attr, mime_type in reprs:+ if not is_callable_method(obj, attr):+ continue++ method = getattr(obj, attr)+ # Try to call _repr_mimebundle_ with include/exclude parameters+ if attr == "_repr_mimebundle_":+ try:+ contents = method(include=[], exclude=[])+ except TypeError:+ # If that fails, call the method without parameters+ contents = method()+ # Remove text/plain from the mimebundle if it's present+ # since there are other representations available+ # N.B. We cannot pass this as an argument to the method+ # because this unfortunately could break some libraries+ # (e.g. ibis)+ if "text/plain" in contents and len(contents) > 1:+ contents.pop("text/plain")+ else:+ contents = method()++ # If the method returns None, continue to the next method+ if contents is None:+ continue++ # Handle the case where the contents are bytes+ if isinstance(contents, bytes):+ # Data should ideally a string, but in case it's bytes,+ # we convert it to a data URL+ data_url = io_to_data_url(+ contents, fallback_mime_type=mime_type+ )+ return (mime_type, data_url or "")++ # Handle markdown and latex+ if mime_type in md_mime_types:+ from marimo._output.md import md++ return ("text/html", md(contents or "").text)++ return (mime_type, contents)++ return ("text/html", "")++ return f_repr++ return Nonediff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.pyindex 53368a74f0..1404dded87 100644--- a/marimo/_output/formatters/structures.py+++ b/marimo/_output/formatters/structures.py@@ -8,6 +8,7 @@ from typing import Any, Unionfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output import formattingfrom marimo._output.formatters.formatter_factory import FormatterFactory+from marimo._output.formatters.repr_formatters import maybe_get_repr_formatterfrom marimo._utils.flatten import CyclicStructureError, flatten@@ -52,6 +53,12 @@ class StructuresFormatter(FormatterFactory):def _format_structure(t: Union[tuple[Any, ...], list[Any], dict[str, Any]],) -> tuple[KnownMimeType, str]:+ # Some objects extend list/tuple/dict, but also have _repr_ methods+ # that we want to use preferentially.+ repr_formatter = maybe_get_repr_formatter(t)+ if repr_formatter is not None:+ return repr_formatter(t)+if t and "matplotlib" in sys.modules:# Special case for matplotlib:#diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex 651361b8b8..f5e3266ea4 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -17,10 +17,8 @@ taking precedence over the MIME protocol.from __future__ import annotations-import inspectimport jsonimport traceback-import typesfrom dataclasses import dataclassfrom html import escapefrom typing import Any, Callable, Optional, Tuple, Type, TypeVar, cast@@ -28,6 +26,7 @@ from typing import Any, Callable, Optional, Tuple, Type, TypeVar, castfrom marimo import _loggers as loggersfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.builder import h+from marimo._output.formatters.repr_formatters import maybe_get_repr_formatterfrom marimo._output.formatters.utils import src_or_src_docfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc@@ -36,6 +35,7 @@ from marimo._plugins.core.media import io_to_data_urlfrom marimo._plugins.stateless.json_output import json_outputfrom marimo._plugins.stateless.mime import mime_rendererfrom marimo._plugins.stateless.plain_text import plain_text+from marimo._utils.methods import is_callable_methodT = TypeVar("T")@@ -136,7 +136,7 @@ def get_formatter(return FORMATTERS[t]# Check for the MIME protocol- if _is_callable_method(obj, "_mime_"):+ if is_callable_method(obj, "_mime_"):def f_mime(obj: T) -> tuple[KnownMimeType, str]:mime, data = obj._mime_() # type: ignore@@ -149,80 +149,7 @@ def get_formatter(return f_mime- md_mime_types: list[KnownMimeType] = [- "text/markdown",- "text/latex",- ]-- # Check for the misc _repr_ methods- # Order dictates preference- reprs: list[Tuple[str, KnownMimeType]] = [- ("_repr_html_", "text/html"), # text/html is preferred first- ("_repr_mimebundle_", "application/vnd.marimo+mimebundle"),- ("_repr_svg_", "image/svg+xml"),- ("_repr_json_", "application/json"),- ("_repr_png_", "image/png"),- ("_repr_jpeg_", "image/jpeg"),- ("_repr_markdown_", "text/markdown"),- ("_repr_latex_", "text/latex"),- ("_repr_text_", "text/plain"), # last- ]- has_possible_repr = any(- _is_callable_method(obj, attr) for attr, _ in reprs- )- if has_possible_repr:- # If there is any match, we return a formatter that calls- # all the possible _repr_ methods, since some can be implemented- # but return None- def f_repr(obj: T) -> tuple[KnownMimeType, str]:- for attr, mime_type in reprs:- if not _is_callable_method(obj, attr):- continue-- method = getattr(obj, attr)- # Try to call _repr_mimebundle_ with include/exclude parameters- if attr == "_repr_mimebundle_":- try:- contents = method(include=[], exclude=[])- except TypeError:- # If that fails, call the method without parameters- contents = method()- # Remove text/plain from the mimebundle if it's present- # since there are other representations available- # N.B. We cannot pass this as an argument to the method- # because this unfortunately could break some libraries- # (e.g. ibis)- if "text/plain" in contents and len(contents) > 1:- contents.pop("text/plain")- else:- contents = method()-- # If the method returns None, continue to the next method- if contents is None:- continue-- # Handle the case where the contents are bytes- if isinstance(contents, bytes):- # Data should ideally a string, but in case it's bytes,- # we convert it to a data URL- data_url = io_to_data_url(- contents, fallback_mime_type=mime_type- )- return (mime_type, data_url or "")-- # Handle markdown and latex- if mime_type in md_mime_types:- from marimo._output.md import md-- return ("text/html", md(contents or "").text)-- return (mime_type, contents)-- return ("text/html", "")-- return f_repr-- return None+ return maybe_get_repr_formatter(obj)@dataclass@@ -402,15 +329,6 @@ class Plain:self.child = child-def _is_callable_method(obj: Any, attr: str) -> bool:- if not hasattr(obj, attr):- return False- method = getattr(obj, attr)- if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):- return False- return callable(method)--@mddocdef iframe(html: str, *, width: str = "100%", height: str = "400px") -> Html:"""diff --git a/marimo/_smoke_tests/third_party/seaborn_example.py b/marimo/_smoke_tests/third_party/seaborn_example.pyindex d0320f3670..2695afcfea 100644--- a/marimo/_smoke_tests/third_party/seaborn_example.py+++ b/marimo/_smoke_tests/third_party/seaborn_example.py@@ -5,9 +5,10 @@# ]# ///# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.1.69"+__generated_with = "0.9.17"app = marimo.App()@@ -20,6 +21,12 @@ def __():return penguins, sns, tips+def __(sns):+ sns.color_palette("pastel")+ return++@app.celldef __(penguins, sns):sns.jointplot(diff --git a/marimo/_utils/methods.py b/marimo/_utils/methods.pynew file mode 100644index 0000000000..4290d08ea5--- /dev/null+++ b/marimo/_utils/methods.py@@ -0,0 +1,14 @@+from __future__ import annotations++import inspect+import types+from typing import Any+++def is_callable_method(obj: Any, attr: str) -> bool:+ if not hasattr(obj, attr):+ return False+ method = getattr(obj, attr)+ if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):+ return False+ return callable(method)diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex 7a078993a8..a62aec1515 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -339,3 +339,33 @@ def test_as_dom_node():assert as_dom_node(True).text == "True"assert as_dom_node(False).text == "False"assert as_dom_node({"key": "value"}).text.startswith("<marimo-json")+++class CustomList(list[int]):+ def _repr_html_(self):+ return f"<h1>{', '.join(map(str, self))}</h1>"+++def test_format_extend_list():+ my_list = CustomList([1, 2, 3])+ assert as_dom_node(my_list).text == "<h1>1, 2, 3</h1>"+++class CustomDict(dict[str, int]):+ def _repr_html_(self):+ return f"<h1>{', '.join(map(str, self.items()))}</h1>"+++def test_format_extend_dict():+ my_dict = CustomDict({"a": 1, "b": 2, "c": 3})+ assert as_dom_node(my_dict).text == "<h1>('a', 1), ('b', 2), ('c', 3)</h1>"+++class CustomTuple(tuple[int, int]):+ def _repr_html_(self):+ return f"<h1>{', '.join(map(str, self))}</h1>"+++def test_format_extend_tuple():+ my_tuple = CustomTuple((1, 2, 3))+ assert as_dom_node(my_tuple).text == "<h1>1, 2, 3</h1>"