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
Accept a covariant Mapping of elements in ui.dictionary and .batch (#10653)
Madan kumar07921bdd2e19
diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.pyindex cafd3bbdab..d7f0cd4049 100644--- a/marimo/_plugins/ui/_impl/batch.py+++ b/marimo/_plugins/ui/_impl/batch.py@@ -14,7 +14,13 @@ from marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementif TYPE_CHECKING:- from collections.abc import Callable, ItemsView, Iterator, ValuesView+ from collections.abc import (+ Callable,+ ItemsView,+ Iterator,+ Mapping,+ ValuesView,+ )U = TypeVar("U")V = TypeVar("V")@@ -22,7 +28,7 @@ V = TypeVar("V")# Explicit type check, since the api has led to some confusion.def validate_and_clone(- elements: dict[str, UIElement[U, V]],+ elements: Mapping[str, UIElement[U, V]],) -> dict[str, UIElement[U, V]]:invalid: list[str] = []new_elements = {}@@ -198,12 +204,12 @@ class batch(_batch_base):Attributes:value (dict): A dict of the batched elements' values.- elements (dict): A dict of the batched elements (clones of the originals).+ elements (Mapping): A dict of the batched elements (clones of the originals).on_change (Optional[Callable]): Optional callback to run when this element's value changes.Args:html (Html): A templated Html object.- elements (dict[str, UIElement]): The UI elements to interpolate into the HTML template.+ elements (Mapping[str, UIElement]): The UI elements to interpolate into the HTML template.on_change (Optional[Callable[[Dict[str, object]], None]], optional): Optional callbackto run when this element's value changes."""@@ -211,7 +217,7 @@ class batch(_batch_base):def __init__(self,html: Html,- elements: dict[str, UIElement[Any, Any]],+ elements: Mapping[str, UIElement[Any, Any]],on_change: Callable[[dict[str, object]], None] | None = None,) -> None:self._html = htmldiff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.pyindex ed49ff8b08..8dacb734f8 100644--- a/marimo/_plugins/ui/_impl/dictionary.py+++ b/marimo/_plugins/ui/_impl/dictionary.py@@ -12,7 +12,7 @@ from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.batch import _batch_base, validate_and_cloneif TYPE_CHECKING:- from collections.abc import Callable+ from collections.abc import Callable, Mapping@mddoc@@ -86,12 +86,12 @@ class dictionary(_batch_base):Attributes:value (dict): A dict holding the values of the UI elements, keyed bytheir names.- elements (dict): A dict of the wrapped elements (clones of the originals).+ elements (Mapping): A dict of the wrapped elements (clones of the originals).on_change (Optional[Callable[[dict[str, object]], None]]): Optional callbackto run when this element's value changes.Args:- elements (dict[str, UIElement[Any, Any]]): A dict mapping names to UI+ elements (Mapping[str, UIElement[Any, Any]]): A dict mapping names to UIelements to include.label (str, optional): A descriptive name for the dictionary. Defaults to "".on_change (Callable[[dict[str, object]], None], optional): Optional callback@@ -100,7 +100,7 @@ class dictionary(_batch_base):def __init__(self,- elements: dict[str, UIElement[Any, Any]],+ elements: Mapping[str, UIElement[Any, Any]],*,label: str = "",on_change: Callable[[dict[str, object]], None] | None = None,diff --git a/tests/_ast/test_app_typing.py b/tests/_ast/test_app_typing.pyindex 6611b35c2f..8ddd312528 100644--- a/tests/_ast/test_app_typing.py+++ b/tests/_ast/test_app_typing.py@@ -242,3 +242,29 @@ class TestBatchTyping:assert_type(parameters.value, dict[str, object])""")+++class TestDictionaryTyping:+ def test_dictionary_accepts_covariant_dict(self) -> None:+ # dict is invariant, so a dict[str, checkbox] was rejected for the old+ # dict[str, UIElement] param; widening it to a covariant Mapping accepts+ # a dict of UIElement subclasses. Regression guard for #10653.+ _check_pyright(+ _PREAMBLE+ + """+ checks: dict[str, mo.ui.checkbox] = {"a": mo.ui.checkbox()}+ d = mo.ui.dictionary(checks)+ assert_type(d.value, dict[str, object])+"""+ )++ def test_validate_and_clone_accepts_covariant_dict(self) -> None:+ _check_pyright(+ """+ import marimo as mo+ from marimo._plugins.ui._impl.batch import validate_and_clone++ checks: dict[str, mo.ui.checkbox] = {"a": mo.ui.checkbox()}+ _cloned = validate_and_clone(checks)+ """+ )diff --git a/tests/_plugins/ui/_impl/test_batch.py b/tests/_plugins/ui/_impl/test_batch.pyindex c390f40298..21929c32e1 100644--- a/tests/_plugins/ui/_impl/test_batch.py+++ b/tests/_plugins/ui/_impl/test_batch.py@@ -1,11 +1,14 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+from types import MappingProxyType+import pytestfrom marimo import mdfrom marimo._output.hypertext import Htmlfrom marimo._plugins import ui+from marimo._plugins.ui._impl.batch import validate_and_clonedef test_batch_rejects_non_ui_elements() -> None:@@ -44,6 +47,19 @@ def test_dictionary_rejects_non_ui_elements() -> None:ui.dictionary({"valid": ui.slider(1, 10), "invalid": "string"}) # type: ignore+def test_validate_and_clone_accepts_readonly_mapping() -> None:+ """`validate_and_clone` accepts any Mapping of UI elements, not just dict."""+ a = ui.text(value="hello")+ elements = MappingProxyType({"a": a})++ cloned = validate_and_clone(elements)++ assert isinstance(cloned, dict)+ assert set(cloned) == {"a"}+ # returns clones, not the originals+ assert cloned["a"]._id != a._id++def test_update_on_frontend_value_change_only() -> None:b = ui.batch(Html("{a} {b}"),diff --git a/tests/_plugins/ui/_impl/test_dictionary.py b/tests/_plugins/ui/_impl/test_dictionary.pyindex 29a9e9b297..ec3545f358 100644--- a/tests/_plugins/ui/_impl/test_dictionary.py+++ b/tests/_plugins/ui/_impl/test_dictionary.py@@ -1,6 +1,8 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+from types import MappingProxyType+import pytestfrom marimo._plugins import ui@@ -32,6 +34,21 @@ def test_dictionary() -> None:assert dictionary.value == {"a": 2, "b": "goodbye", "c": 1}+def test_dictionary_accepts_readonly_mapping() -> None:+ # `elements` is typed as a covariant Mapping, so any read-only mapping of+ # UI elements (not just a plain dict) must be accepted and cloned.+ a = ui.text(value="hello")+ b = ui.slider(1, 10, value=2)+ elements = MappingProxyType({"a": a, "b": b})++ dictionary = ui.dictionary(elements)++ assert dictionary.value == {"a": "hello", "b": 2}+ # elements are cloned, not the originals+ assert dictionary.elements["a"]._id != a._id+ assert dictionary.elements["b"]._id != b._id++def test_nested_dict() -> None:inner = ui.dictionary({"slider": ui.slider(1, 10)})outer = ui.dictionary({"inner": inner})