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
feat: _display_ protocol (#2471)
Akshay Agrawal3f175b1087f3
diff --git a/docs/guides/integrating_with_marimo/displaying_objects.md b/docs/guides/integrating_with_marimo/displaying_objects.mdindex bdb71a08c6..a051f0081b 100644--- a/docs/guides/integrating_with_marimo/displaying_objects.md+++ b/docs/guides/integrating_with_marimo/displaying_objects.md@@ -7,9 +7,50 @@ seaborn, Plotly, altair pandas, and more. These rich representations aredisplayed for the last expression of a cell, or when using[`mo.output.append`](#marimo.output.append).-You can register rich displays with marimo for your own objects.+You can register rich displays with marimo for your own objects. You have+three options:-### Option 1: Implement an IPython `_repr_*_()` method+1. Implement a `_display_()` method+2. Implement a `_mime_()` method+3. Implement an IPython-style `_repr_*_()` method++If you can't modify the object, you can also add a formatter to the marimo+library (option 4).++The return value of these methods determines what is shown. `_display_`+has the highest precedence, then built-in formatters, then `_mime_`, then `IPython` style `_repr_*_`+methods.+++### Option 1: Implement a `_display_()` method++If an object implements a `_display_()`, marimo will use its return value+to visualize the object as an output.++For example:++```+class Dice:+ def _display_(self):+ import random++ return f"You rolled {random.randint(0, 7)}"+```++The return value of `_display_` can be any Python object, for example a+a matplotlib plot, a dataframe, a list, `mo.Html`, or a `mo.ui` element, and+marimo will attempt to display it.++In addition to being the most convenient way do define a custom display in+marimo (in terms of syntax), it is also helpful for library developers: this+option lets you make an object showable in marimo without adding marimo as a+dependency to your project.++However, if you need to display an object that marimo does not know how to+render (for example, maybe you are building a new plotting library), then+you need to consider of the other options below.++### Option 2: Implement an IPython `_repr_*_()` methodmarimo can render objects that implement[IPython's `_repr_*_()` protocol](https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods)@@ -38,7 +79,7 @@ We support the following methods:- `_repr_latex_`- `_repr_text_`-### Option 2: Implement a `_mime_` method+### Option 3: Implement a `_mime_` methodWhen displaying an object, marimo's media viewer checks for the presence of amethod called `_mime_`. This method should take no arguments and return@@ -102,13 +143,13 @@ a tuple of two strings, the [mime type](https://developer.mozilla.org/en-US/docsImage("https://raw.githubusercontent.com/marimo-team/marimo/main/docs/_static/marimo-logotype-thick.svg")```-### Option 3: Add a formatter to the marimo repo+### Option 4: Add a formatter to the marimo repoThe recommended way to render rich displays of objects in marimo is to-implement either the IPython `_repr_*_()_` protocol or marimo's `_mime_()`-protocol. If you are a a user of a library that does not render properly in-marimo, consider asking the library maintainers to implement one of these-protocols.+implement `_display_` if possible, otherwise either the IPython `_repr_*_()_`+protocol or marimo's `_mime_()` protocol. If you are a a user of a library that+does not render properly in marimo, consider asking the library maintainers to+implement one of these protocols.If it is not possible to implement a renderer protocol on the typeyou want displayed, we will consider contributions to add formatters to thediff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex f5e3266ea4..0c2f919ab1 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -112,6 +112,7 @@ def get_formatter(# a kernel (eg, in a unit test or when run as a Python script)register_formatters()+ # Plain opts out of opinionated formattersif isinstance(obj, Plain):child_formatter = get_formatter(obj.child, include_opinionated=False)if child_formatter:@@ -122,6 +123,20 @@ def get_formatter(return plain_formatter+ # Display protocol has the highest precedence+ if is_callable_method(obj, "_display_"):++ def f_mime(obj: T) -> tuple[KnownMimeType, str]:+ displayable_object = obj._display_() # type: ignore+ _f = get_formatter(displayable_object)+ if _f is not None:+ return _f(displayable_object)+ else:+ return as_html(displayable_object)._mime_()++ return f_mime++ # Formatters dict gets precedenceif include_opinionated:if type(obj) in OPINIONATED_FORMATTERS:return OPINIONATED_FORMATTERS[type(obj)]diff --git a/marimo/_utils/methods.py b/marimo/_utils/methods.pyindex 4290d08ea5..17a44277cb 100644--- a/marimo/_utils/methods.py+++ b/marimo/_utils/methods.py@@ -8,6 +8,7 @@ from typing import Anydef 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 Falsediff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex 1bcd04da62..53d30f1e7c 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -49,18 +49,18 @@ def test_formatters_with_opinionated_formatter() -> None:# Happy pathobj = ["test"]formatter = get_formatter(obj)- assert formatter+ assert formatter is not Noneassert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')# With Plainobj = Plain(["test"])formatter = get_formatter(obj)- assert formatter+ assert formatter is not Noneassert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')# With pandas DataFrameformatter = get_formatter(pd_df)- assert formatter+ assert formatter is not Nonemime, content = formatter(pd_df)assert mime == "text/html"assert "<marimo-table" in content@@ -68,14 +68,14 @@ def test_formatters_with_opinionated_formatter() -> None:# With plain DataFrame + Plainobj = Plain(pd_df)formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert "<marimo-table" not in content# With polars DataFrameformatter = get_formatter(pl_df)- assert formatter+ assert formatter is not Nonemime, content = formatter(pl_df)assert mime == "text/html"assert "<marimo-table" in content@@ -83,7 +83,7 @@ def test_formatters_with_opinionated_formatter() -> None:# With plain DataFrame + Plainobj = Plain(pl_df)formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert "<marimo-table" not in content@@ -151,7 +151,7 @@ def test_repr_markdown():obj = ReprMarkdown()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert (@@ -167,7 +167,7 @@ def test_repr_latex():obj = ReprLatex()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert (@@ -183,7 +183,7 @@ def test_repr_html():obj = ReprHTML()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert content == "<h1>Hello, World!</h1>"@@ -198,7 +198,7 @@ def test_repr_png():obj = ReprPNG()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "image/png"assert content == png@@ -213,7 +213,7 @@ def test_repr_jpeg():obj = ReprJPEG()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "image/jpeg"assert content == jpeg@@ -228,7 +228,7 @@ def test_repr_svg():obj = ReprSVG()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "image/svg+xml"assert content == svg@@ -241,7 +241,7 @@ def test_repr_json():obj = ReprJSON()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/json"assert content == {"message": "Hello, World!"}@@ -257,7 +257,7 @@ def test_prefer_repr_html_over_repr_markdown():obj = ReprBoth()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "text/html"assert content == "<h6>Hello, World!</h6>"@@ -273,7 +273,7 @@ def test_repr_mimebundle():obj = ReprMimeBundle()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/vnd.marimo+mimebundle"assert content == {"application/json": {"message": "Hello, World!"}}@@ -290,7 +290,7 @@ def test_repr_mimebundle_with_exclude():obj = ReprMimeBundle()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/vnd.marimo+mimebundle"assert content == {"application/json": {"message": "Hello, World!"}}@@ -309,7 +309,7 @@ def test_repr_returns_none():obj = ReprNone()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/json"assert content == "{}"@@ -325,7 +325,7 @@ def test_repr_empty_string():obj = ReprNone()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/json"assert content == ""@@ -380,7 +380,7 @@ def test_repr_mimebundle_with_markdown():obj = ReprMimeBundleWithMarkdown()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/vnd.marimo+mimebundle"assert content == {@@ -398,7 +398,7 @@ def test_repr_mimebundle_with_markdown():obj = ReprMimeBundleWithMarkdownAndHtml()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/vnd.marimo+mimebundle"assert content == {@@ -416,10 +416,28 @@ def test_repr_mimebundle_with_latex():obj = ReprMimeBundleWithLatex()formatter = get_formatter(obj)- assert formatter+ assert formatter is not Nonemime, content = formatter(obj)assert mime == "application/vnd.marimo+mimebundle"assert content == {"text/html": '<span class="markdown prose dark:prose-invert"><span class="paragraph"><marimo-tex class="arithmatex">||(e^x||)</marimo-tex></span></span>',"text/latex": r"$e^x$",}+++def test_display_protocol_takes_precedence() -> None:+ register_formatters()++ class Foo(list):+ def _display_(self):+ return "foo"++ def _repr_html_(self):+ return "<h1>Hello, World!</h1>"++ obj = Foo()+ formatter = get_formatter(obj)+ assert formatter is not None+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert content == "<span>foo</span>"