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
fix: raise an error for invalid batch usage (#7140)
Dylan Madisetti1fe8e40def4e
diff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.pyindex 13e29817c0..fbc556f4f0 100644--- a/marimo/_plugins/ui/_impl/batch.py+++ b/marimo/_plugins/ui/_impl/batch.py@@ -7,6 +7,7 @@ from typing import (Callable,Final,Optional,+ TypeVar,)from marimo._output.hypertext import Html@@ -17,6 +18,30 @@ from marimo._plugins.ui._core.ui_element import UIElementif TYPE_CHECKING:from collections.abc import ItemsView, Iterator, ValuesView+U = TypeVar("U")+V = TypeVar("V")+++# Explicit type check, since the api has led to some confusion.+def validate_and_clone(+ elements: dict[str, UIElement[U, V]],+) -> dict[str, UIElement[U, V]]:+ invalid: list[str] = []+ new_elements = {}+ for key, element in elements.items():+ if not isinstance(element, UIElement):+ invalid.append(key)+ else:+ new_elements[key] = element._clone()++ if invalid:+ invalid_keys = ", ".join(f"'{k}'" for k in invalid)+ raise ValueError(+ f"`.batch` only accepts UIElements as arguments. "+ f"Invalid keys: {invalid_keys}"+ )+ return new_elements+# - Frontend type is a dict {label => value update}# - Python type is a dict mapping label -> value@@ -188,7 +213,7 @@ class batch(_batch_base):on_change: Optional[Callable[[dict[str, object]], None]] = None,) -> None:self._html = html- elements = {key: element._clone() for key, element in elements.items()}+ elements = validate_and_clone(elements)super().__init__(html=Html(self._html.text.format(**elements)),elements=elements,diff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.pyindex 974ef9f178..390af8518f 100644--- a/marimo/_plugins/ui/_impl/dictionary.py+++ b/marimo/_plugins/ui/_impl/dictionary.py@@ -9,7 +9,7 @@ from marimo._output.rich_help import mddocfrom marimo._plugins.stateless.flex import hstack, vstackfrom marimo._plugins.stateless.json_output import json_outputfrom marimo._plugins.ui._core.ui_element import UIElement-from marimo._plugins.ui._impl.batch import _batch_base+from marimo._plugins.ui._impl.batch import _batch_base, validate_and_clone@mddoc@@ -120,7 +120,7 @@ class dictionary(_batch_base):# additional logic were added to the frontend DictPlugin to spy on# marimoValueUpdateEvents of children), and in any case will not# trigger cells that ref the dictionary to run, leading to confusion- elements = {key: element._clone() for key, element in elements.items()}+ elements = validate_and_clone(elements)self._label = label# slot a JSON tree viewer as the contents of this elementdiff --git a/tests/_plugins/ui/_impl/test_batch.py b/tests/_plugins/ui/_impl/test_batch.pyindex 227cf0ef93..c285ef6456 100644--- a/tests/_plugins/ui/_impl/test_batch.py+++ b/tests/_plugins/ui/_impl/test_batch.py@@ -1,10 +1,49 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import pytest++from marimo import mdfrom marimo._output.hypertext import Htmlfrom marimo._plugins import ui+def test_batch_rejects_non_ui_elements() -> None:+ """Test that batch raises ValueError for non-UIElement arguments."""+ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ md("Example {thing}").batch(thing="thing") # type: ignore++ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ md("Example {thing}").batch(thing=42) # type: ignore++ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ md("Example {thing}").batch(thing={"key": "value"}) # type: ignore+++def test_dictionary_rejects_non_ui_elements() -> None:+ """Test that dictionary raises ValueError for non-UIElement arguments."""+ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ ui.dictionary({"hi": 1}) # type: ignore++ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ ui.dictionary({"text": "string"}) # type: ignore++ with pytest.raises(+ ValueError, match="`.batch` only accepts UIElements as arguments"+ ):+ ui.dictionary({"valid": ui.slider(1, 10), "invalid": "string"}) # type: ignore++def test_update_on_frontend_value_change_only() -> None:b = ui.batch(Html("{a} {b}"),