Skip to content

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.

fix: more ipython display coverage, add tests (#3804)

Myles Scolnick0f66370b51c2
diff --git a/marimo/_output/formatters/ipython_formatters.py b/marimo/_output/formatters/ipython_formatters.py
index 7bd1e41cf0..afeba2526f 100644
--- a/marimo/_output/formatters/ipython_formatters.py
+++ b/marimo/_output/formatters/ipython_formatters.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import functools
+from dataclasses import dataclass
from typing import Any, Callable
from marimo._messaging.mimetypes import KnownMimeType
@@ -29,15 +30,32 @@ class IPythonFormatter(FormatterFactory):
# IPython.display.display returns a DisplayHandle, which
# can be used to update the displayed object. We don't support
# that yet ...
+
+ # If clear is True, clear the output before displaying
if kwargs.pop("clear", False):
_output.clear()
+
+ raw = kwargs.pop("raw", False)
for value in objs:
- _output.append(value)
+ # raw means it's a mimebundle, with the key (mime) and value (raw data)
+ if raw and isinstance(value, dict):
+ _output.append(ReprMimeBundle(value))
+ else:
+ _output.append(value)
IPython.display.display = display
+ # Patching display_functions handles display_markdown, display_x, etc.
+ try:
+ IPython.core.display_functions.display = display # type: ignore
+ except AttributeError:
+ pass
def unpatch() -> None:
- IPython.display.display = old_display
+ IPython.display.display = old_display # type: ignore
+ try:
+ IPython.core.display_functions.display = old_display # type: ignore
+ except AttributeError:
+ pass
@formatting.formatter(
IPython.display.HTML # type:ignore
@@ -58,3 +76,16 @@ class IPythonFormatter(FormatterFactory):
return ("text/html", data)
return unpatch
+
+
+@dataclass
+class ReprMimeBundle:
+ data: dict[str, Any]
+
+ def _repr_mimebundle_(
+ self,
+ include: Any = None,
+ exclude: Any = None,
+ ) -> dict[str, Any]:
+ del include, exclude
+ return self.data
diff --git a/marimo/_smoke_tests/compat/ipython_display.py b/marimo/_smoke_tests/compat/ipython_display.py
index 3267f4be30..5c1a222c27 100644
--- a/marimo/_smoke_tests/compat/ipython_display.py
+++ b/marimo/_smoke_tests/compat/ipython_display.py
@@ -2,19 +2,114 @@
# requires-python = ">=3.12"
# dependencies = [
# "ipython==8.31.0",
+# "marimo",
+# "numpy==2.2.3",
# ]
# ///
import marimo
-__generated_with = "0.10.9"
+__generated_with = "0.11.4"
app = marimo.App(width="medium")
@app.cell
def _():
- from IPython.display import SVG, Markdown, display
- return Markdown, SVG, display
+ from IPython.display import (
+ Audio,
+ display,
+ HTML,
+ Image,
+ JSON,
+ Javascript,
+ Latex,
+ Markdown,
+ Math,
+ # PDF,
+ Pretty,
+ SVG,
+ Video,
+ YouTubeVideo,
+ Code,
+ IFrame,
+ )
+ return (
+ Audio,
+ Code,
+ HTML,
+ IFrame,
+ Image,
+ JSON,
+ Javascript,
+ Latex,
+ Markdown,
+ Math,
+ Pretty,
+ SVG,
+ Video,
+ YouTubeVideo,
+ display,
+ )
+
+
+def _(HTML):
+ html = HTML("<h1>Hello World</h1><p style='color: blue;'>This is HTML</p>")
+ html
+ return (html,)
+
+
+def _(Image):
+ # Using a sample image URL
+ image = Image(url="https://marimo.io/logo.png", width=100)
+ image
+ return (image,)
+
+
+def _(JSON):
+ json_data = JSON(
+ {
+ "name": "marimo",
+ "type": "notebook",
+ "features": ["interactive", "reactive"],
+ }
+ )
+ json_data
+ return (json_data,)
+
+
+def _(Javascript):
+ # Not yet supported
+ js = Javascript("alert('Hello from JavaScript!');")
+ js
+ return (js,)
+
+
+def _(Latex):
+ latex = Latex(r"\begin{align}f(x) &= x^2\\g(x) &= \frac{1}{x}\end{align}")
+ latex
+ return (latex,)
+
+
+def _(Math):
+ math = Math(
+ r"\frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum_{k=0}^\infty \frac{(4k)!(1103+26390k)}{(k!)^4 396^{4k}}"
+ )
+ math
+ return (math,)
+
+
+def _(Pretty):
+ _data = '{"complex": [1, 2, {"nested": "structure"}]}'
+ pretty = Pretty(_data)
+ pretty
+ return (pretty,)
@app.cell
@@ -26,21 +121,162 @@ def _(SVG):
return (svg,)
+def _(Audio):
+ # Example with synthesized audio data
+ import numpy as np
+
+ sample_rate = 44100
+ t = np.linspace(0, 2, 2 * sample_rate)
+ data = np.sin(2 * np.pi * 440 * t) # 440 Hz sine wave
+ audio = Audio(data=data, rate=sample_rate)
+ audio
+ return audio, data, np, sample_rate, t
+
+
+def _(Video):
+ # Using a sample video URL
+ video = Video("https://www.w3schools.com/html/mov_bbb.mp4")
+ video
+ return (video,)
+
+
+def _(YouTubeVideo):
+ # Example YouTube video
+ yt = YouTubeVideo("dQw4w9WgXcQ")
+ yt
+ return (yt,)
+
+
+def _(Code):
+ code = Code(
+ """def hello_world():
+ print("Hello, World!")""",
+ language="python",
+ )
+ code
+ return (code,)
+
+
+def _(IFrame):
+ iframe = IFrame("https://marimo.io", width=800, height=450)
+ iframe
+ return (iframe,)
+
+
@app.cell
def _(Markdown):
markdown = Markdown(
- "## This is a Markdown Example\nHere is a list:\n- Item 1\n- Item 2\n- Item 3"
+ """
+ ## This is a Markdown Example
+ Here is a list:
+ - Item 1
+ - Item 2
+ - Item 3
+
+ And some **bold** and *italic* text.
+ """
)
markdown
return (markdown,)
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""# Display Commands""")
+ return
+
+
@app.cell
-def _(display, markdown, svg):
- display(markdown)
- display(svg) # does not work, not sure why
+def _(Markdown, display):
+ display(Markdown("**hello**"))
+ display(Markdown("_goodbye*"))
return
+def _():
+ from IPython.display import (
+ display_pretty,
+ display_html,
+ display_markdown,
+ display_svg,
+ display_png,
+ display_jpeg,
+ display_latex,
+ display_json,
+ display_javascript,
+ display_pdf,
+ )
+ return (
+ display_html,
+ display_javascript,
+ display_jpeg,
+ display_json,
+ display_latex,
+ display_markdown,
+ display_pdf,
+ display_png,
+ display_pretty,
+ display_svg,
+ )
+
+
+def _(
+ display_html,
+ display_jpeg,
+ display_png,
+ display_pretty,
+ display_svg,
+):
+ # Working
+ display_pretty("hello", raw=True)
+ display_html("<h1 style='color: blue'>Hello World</h1>", raw=True)
+ display_svg(
+ '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>',
+ raw=True,
+ )
+ display_png("https://marimo.io/favicon.ico", raw=True)
+ display_jpeg("https://marimo.io/favicon.ico", raw=True)
+ return
+
+
+def _(
+ display_javascript,
+ display_json,
+ display_latex,
+ display_markdown,
+ display_pdf,
+):
+ # Broken or not yet supported
+ display_markdown("## Hello World", raw=True)
+ display_latex(
+ r"\begin{align}f(x) &= x^2\\g(x) &= \frac{1}{x}\end{align}", raw=True
+ )
+ display_json(
+ {
+ "name": "marimo",
+ "type": "notebook",
+ "features": ["interactive", "reactive"],
+ },
+ raw=True,
+ )
+ display_javascript("alert('Hello from JavaScript!');", raw=True)
+ display_pdf("https://marimo.io/logo.png", raw=True)
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
if __name__ == "__main__":
app.run()
diff --git a/tests/_output/formatters/test_ipython_formatters.py b/tests/_output/formatters/test_ipython_formatters.py
new file mode 100644
index 0000000000..b42eb773b1
--- /dev/null
+++ b/tests/_output/formatters/test_ipython_formatters.py
@@ -0,0 +1,78 @@
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._output.formatters.ipython_formatters import (
+ IPythonFormatter,
+ ReprMimeBundle,
+)
+from marimo._output.formatting import get_formatter
+
+HAS_DEPS = DependencyManager.ipython.has()
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+def test_register_html_display():
+ from IPython.display import HTML
+
+ IPythonFormatter().register()
+
+ # Test HTML with direct content
+ html = HTML("<div>Hello World</div>")
+ formatter = get_formatter(html)
+ assert formatter is not None
+ result = formatter(html)
+ assert result == ("text/html", "<div>Hello World</div>")
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+@patch("marimo._runtime.output._output.append")
+def test_display_patch(mock_append: MagicMock):
+ from IPython.display import HTML, display
+
+ unpatch = IPythonFormatter().register()
+ try:
+ # Test regular display
+ obj = HTML("<div>Test</div>")
+ display(obj)
+ mock_append.assert_called_once_with(obj)
+ mock_append.reset_mock()
+
+ # Test raw mimebundle display
+ mimebundle = {"text/html": "<div>Raw Test</div>"}
+ display(mimebundle, raw=True)
+ mock_append.assert_called_once()
+ assert isinstance(mock_append.call_args[0][0], ReprMimeBundle)
+ assert mock_append.call_args[0][0].data == mimebundle
+ finally:
+ unpatch()
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+def test_repr_mimebundle():
+ data = {"text/html": "<div>Test</div>", "text/plain": "Test"}
+ bundle = ReprMimeBundle(data)
+ assert bundle._repr_mimebundle_() == data
+ # Test that include/exclude params are ignored
+ assert bundle._repr_mimebundle_(include=["text/html"]) == data
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+@patch("marimo._runtime.output._output.append")
+def test_display_html(mock_append: MagicMock):
+ from IPython.display import display_html
+
+ unpatch = IPythonFormatter().register()
+
+ try:
+ display_html("<div>Test</div>", raw=True)
+ mock_append.assert_called_once()
+ assert isinstance(mock_append.call_args[0][0], ReprMimeBundle)
+ assert mock_append.call_args[0][0].data == {
+ "text/html": "<div>Test</div>"
+ }
+ finally:
+ unpatch()