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
feat(ui): default dropdown to first option when allow_select_none is … (#11238)
Niklas von Moers2b8481c71a8f
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex bb54b6e20d..80d2ca0d04 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -1034,6 +1034,7 @@ class dropdown(UIElement[list[str], Any]):value (str, optional): Default option name. Defaults to None.allow_select_none (bool, optional): Whether to include special option ("--")for a None value; when None, defaults to True when value is None.+ If False and value is None, the first option is used as the value.Defaults to None.searchable (bool, optional): Whether to enable search functionality.Defaults to False.@@ -1081,15 +1082,17 @@ class dropdown(UIElement[list[str], Any]):"is reserved by marimo; please use another name.")- self.options = options- initial_value = [value] if value is not None else []if allow_select_none is None:allow_select_none = value is Noneelif not allow_select_none and value is None:- raise ValueError(- "when `allow_select_none` is False, a non-None default value "- "must be provided."- )+ if not options:+ raise ValueError(+ "when `allow_select_none` is False, `options` must not be empty."+ )+ value = next(iter(options))++ self.options = options+ initial_value = [value] if value is not None else []super().__init__(component_name=dropdown._name,diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex b24e11947e..6c2d70728d 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -527,6 +527,24 @@ def test_dropdown_duplicate_option_names_raise() -> None:assert len(dd.options) == 2+def test_dropdown_disallow_select_none_infers_value() -> None:+ dd = ui.dropdown(options=["1", "2", "3"], allow_select_none=False)+ assert dd.value == "1"++ dd = ui.dropdown(options={"1": "a", "2": "b"}, allow_select_none=False)+ assert dd.value == "a"+++def test_dropdown_disallow_select_none_with_empty_options_raises() -> None:+ msg = "when `allow_select_none` is False, `options` must not be empty"++ with pytest.raises(ValueError, match=msg):+ ui.dropdown(options={}, allow_select_none=False)++ with pytest.raises(ValueError, match=msg):+ ui.dropdown(options=[], allow_select_none=False)++def test_multiselect_duplicate_option_names_raise() -> None:with pytest.raises(ValueError, match="Duplicate option name"):ui.multiselect(options=["a", "a", "b"])