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
allow for __contains__ and __getitem__ in anywidget (#7846)
vincent d warmerdame624c35028ff
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 9297c75f00..b27e32de16 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -330,3 +330,11 @@ class anywidget(UIElement[WireFormat, T]):except AttributeError:return Nonereturn getattr(self.widget, name)++ def __getitem__(self, key: Any) -> Any:+ """Forward __getitem__ to the wrapped widget."""+ return self.widget[key]++ def __contains__(self, key: Any) -> bool:+ """Forward __contains__ to the wrapped widget."""+ return key in self.widgetdiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex e2a1e0dc11..e4b25ef5f5 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -519,6 +519,36 @@ x = as_marimo_element.countwrapped._update({"d": 4})assert wrapped.value == {"a": 100, "b": 200, "c": 300, "d": 4}+ @staticmethod+ async def test_getitem_and_contains() -> None:+ """Test that __getitem__ and __contains__ are forwarded to the widget."""+ from typing import Any++ class DictLikeWidget(_anywidget.AnyWidget):+ _esm = ""+ data = traitlets.Dict({"a": 1, "b": 2}).tag(sync=True)++ def __getitem__(self, key: str) -> Any:+ return self.data[key]++ def __contains__(self, key: str) -> bool:+ return key in self.data++ wrapped = anywidget(DictLikeWidget())++ # Test __getitem__ forwarding+ assert wrapped["a"] == 1+ assert wrapped["b"] == 2++ # Test __contains__ forwarding+ assert "a" in wrapped+ assert "b" in wrapped+ assert "c" not in wrapped++ # Test KeyError propagation+ with pytest.raises(KeyError):+ _ = wrapped["nonexistent"]+@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")class TestWireFormat: