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.

feat: support ipython display update (#4772)

brenoca6529d5d130e3
diff --git a/marimo/_output/formatters/ipython_formatters.py b/marimo/_output/formatters/ipython_formatters.py
index afeba2526f..3a1193ac70 100644
--- a/marimo/_output/formatters/ipython_formatters.py
+++ b/marimo/_output/formatters/ipython_formatters.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import functools
from dataclasses import dataclass
-from typing import Any, Callable
+from typing import Any, Callable, Optional
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.builder import h
@@ -21,39 +21,109 @@ class IPythonFormatter(FormatterFactory):
from marimo._output import formatting
from marimo._runtime.output import _output
+ # Dictionary to store display objects by ID
+ display_objects: dict[str, Any] = {}
+
old_display = IPython.display.display
- # monkey patch IPython.display.display, which imperatively writes
- # outputs to the frontend
+ old_update_display = getattr(IPython.display, "update_display", None)
- @functools.wraps(old_display)
- def display(*objs: Any, **kwargs: Any) -> None:
- # IPython.display.display returns a DisplayHandle, which
- # can be used to update the displayed object. We don't support
- # that yet ...
+ # DisplayHandle class to match IPython's API
+ class DisplayHandle:
+ def __init__(self, display_id: str):
+ self.display_id = display_id
+
+ def update(self, obj: Any, **kwargs: Any) -> None:
+ update_display(obj, display_id=self.display_id, **kwargs)
+ # Monkey patch IPython.display.display, which imperatively writes
+ # outputs to the frontend
+ @functools.wraps(old_display)
+ def display(*objs: Any, **kwargs: Any) -> Optional[DisplayHandle]:
# If clear is True, clear the output before displaying
if kwargs.pop("clear", False):
_output.clear()
+ # Get display_id if provided
+ display_id = kwargs.pop("display_id", None)
+ if display_id is True: # Generate a new display_id if True
+ import uuid
+
+ display_id = str(uuid.uuid4())
+
raw = kwargs.pop("raw", False)
for value in objs:
# raw means it's a mimebundle, with the key (mime) and value (raw data)
if raw and isinstance(value, dict):
- _output.append(ReprMimeBundle(value))
+ output_value = ReprMimeBundle(value)
else:
- _output.append(value)
+ output_value = value
+
+ # Store the object if display_id is provided
+ if display_id is not None:
+ display_objects[display_id] = output_value
+
+ _output.append(output_value)
+
+ # Return a DisplayHandle if display_id is provided
+ if display_id is not None:
+ return DisplayHandle(display_id)
+ return None
+
+ # Implement update_display function
+ def update_display(
+ obj: Any, *, display_id: str, **kwargs: Any
+ ) -> None:
+ """Update an existing display by id
+
+ Parameters
+ ----------
+ obj : Any
+ The object with which to update the display
+ display_id : str
+ The id of the display to update
+ """
+ if display_id not in display_objects:
+ return
+
+ # Clear the output before updating
+ # _output.clear()
+
+ # Update the stored object
+ raw = kwargs.pop("raw", False)
+ if raw and isinstance(obj, dict):
+ display_objects[display_id] = ReprMimeBundle(obj)
+ else:
+ display_objects[display_id] = obj
+ # Append the updated object to the output
+ _output.replace(display_objects[display_id])
+
+ # Patch both display and update_display
IPython.display.display = display
+ IPython.display.update_display = update_display
+
# Patching display_functions handles display_markdown, display_x, etc.
try:
IPython.core.display_functions.display = display # type: ignore
+ IPython.core.display_functions.update_display = update_display # type: ignore
except AttributeError:
pass
def unpatch() -> None:
IPython.display.display = old_display # type: ignore
+ if old_update_display is not None:
+ IPython.display.update_display = old_update_display # type: ignore
+ else:
+ delattr(IPython.display, "update_display")
+
try:
IPython.core.display_functions.display = old_display # type: ignore
+ if old_update_display is not None:
+ IPython.core.display_functions.update_display = (
+ old_update_display # type: ignore
+ )
+ else:
+ delattr(IPython.core.display_functions, "update_display")
except AttributeError:
pass
diff --git a/tests/_output/formatters/test_ipython_update.py b/tests/_output/formatters/test_ipython_update.py
new file mode 100644
index 0000000000..1747bd96b2
--- /dev/null
+++ b/tests/_output/formatters/test_ipython_update.py
@@ -0,0 +1,79 @@
+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,
+)
+
+HAS_DEPS = DependencyManager.ipython.has()
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+@patch("marimo._runtime.output._output.replace")
+@patch("marimo._runtime.output._output.append")
+def test_display_update(mock_append: MagicMock, mock_replace: MagicMock):
+ """Test that display with display_id returns a handle and update works."""
+ # Import IPython before patching to ensure we get the module
+ import IPython.display
+
+ # Apply our formatter patch
+ unpatch = IPythonFormatter().register()
+
+ try:
+ # Now use the patched functions
+ obj1 = IPython.display.HTML("<div>Initial Content</div>")
+ handle = IPython.display.display(obj1, display_id="test-id")
+
+ # Verify handle was returned and append was called
+ assert handle is not None
+ assert handle.display_id == "test-id"
+ mock_append.assert_called_once_with(obj1)
+ mock_append.reset_mock()
+
+ # Test update_display
+ obj2 = IPython.display.HTML("<div>Updated Content</div>")
+ IPython.display.update_display(obj2, display_id="test-id")
+
+ # Verify replace was called
+ mock_replace.assert_called_once_with(obj2)
+
+ # Test handle.update method
+ mock_replace.reset_mock()
+
+ obj3 = IPython.display.HTML("<div>Handle Updated Content</div>")
+ handle.update(obj3)
+
+ # Verify replace was called
+ mock_replace.assert_called_once_with(obj3)
+
+ finally:
+ unpatch()
+
+
[email protected](not HAS_DEPS, reason="IPython not installed")
+@patch("marimo._runtime.output._output.append")
+def test_display_auto_id(mock_append: MagicMock):
+ """Test that display with display_id=True auto-generates an ID."""
+ # Import IPython before patching
+ import IPython.display
+
+ # Apply our formatter patch
+ unpatch = IPythonFormatter().register()
+
+ try:
+ # Test display with auto-generated display_id
+ obj = IPython.display.HTML("<div>Auto ID Content</div>")
+ handle = IPython.display.display(obj, display_id=True)
+
+ # Verify handle was returned with a UUID
+ assert handle is not None
+ assert isinstance(handle.display_id, str)
+ assert len(handle.display_id) > 0
+ mock_append.assert_called_once_with(obj)
+
+ finally:
+ unpatch()