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: when a widget is unhashable don't cache it (#4099)

Myles Scolnick1275971cfc07
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index 15c8f9fa1c..55609bf296 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -28,9 +28,14 @@ cache: dict[Any, UIElement[Any, Any]] = weakref.WeakKeyDictionary() # type: ign
def from_anywidget(widget: AnyWidget) -> UIElement[Any, Any]:
"""Create a UIElement from an AnyWidget."""
- if widget not in cache:
- cache[widget] = anywidget(widget) # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
- return cache[widget]
+ try:
+ if widget not in cache:
+ cache[widget] = anywidget(widget) # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
+ return cache[widget]
+ except TypeError as e:
+ # Unhashable widgets can't be used as keys in a WeakKeyDictionary
+ LOGGER.warning(e)
+ return anywidget(widget)
T = dict[str, Any]
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index ee6e7f5801..500580d958 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -6,7 +6,7 @@ from hashlib import md5
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.from_anywidget import anywidget
+from marimo._plugins.ui._impl.from_anywidget import anywidget, from_anywidget
from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -389,3 +389,19 @@ x = as_marimo_element.count
nested_state = {"y": {"key": "value"}}
wrapped._update(nested_state)
assert wrapped.value == {"x": 42, "y": {"key": "value"}}
+
+ @staticmethod
+ def test_unhashable_widget() -> None:
+ """Test that unhashable widgets can still be wrapped."""
+
+ # Create a widget with an unhashable trait (list)
+ class UnhashableWidget(_anywidget.AnyWidget):
+ _esm = ""
+
+ def __hash__(self) -> int:
+ raise TypeError("Unhashable widget")
+
+ # This should work without errors despite the widget being unhashable
+ widget = UnhashableWidget()
+ wrapped = from_anywidget(widget)
+ assert wrapped is not None