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.

improvement: better errors when mutated value or on_change (#1604)

Myles Scolnick9d722f4378b8
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 95f705d082..e5bef61d98 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -113,6 +113,14 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
slotted_html: any html to slot in the custom element
functions: any functions to register with the graph
"""
+ # Validate parameters from a user
+ if not isinstance(component_name, str):
+ raise TypeError("component_name must be a string")
+ if label is not None and not isinstance(label, str):
+ raise TypeError("label must be a string or None")
+ if on_change is not None and not callable(on_change):
+ raise TypeError("on_change must be a callable or None")
+
# arguments stored in signature order for cloning
self._args = (
component_name,
@@ -269,6 +277,23 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
)
return self._value
+ @value.setter
+ def value(self, value: T) -> None:
+ del value
+ raise RuntimeError(
+ "Setting the value of a UIElement is not allowed. "
+ "If you need to imperatively set the value of a UIElement, "
+ "consider using mo.state()."
+ )
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ if name == "on_change":
+ raise RuntimeError(
+ "Setting the on_change handler of a UIElement is not allowed. "
+ "You must set the on_change in the constructor."
+ )
+ super().__setattr__(name, value)
+
@mddoc
def form(
self,
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index d579503e34..9347e82b04 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -355,3 +355,8 @@ class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):
" based on the selection.",
)
return value
+
+ @value.setter
+ def value(self, value: pd.DataFrame) -> None:
+ del value
+ raise RuntimeError("Setting the value of a UIElement is not allowed.")
diff --git a/marimo/_smoke_tests/no_mutating.py b/marimo/_smoke_tests/no_mutating.py
new file mode 100644
index 0000000000..2037873efd
--- /dev/null
+++ b/marimo/_smoke_tests/no_mutating.py
@@ -0,0 +1,38 @@
+import marimo
+
+__generated_with = "0.6.17"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ text = mo.ui.text(on_change=print)
+ return text,
+
+
+def __(text):
+ text.on_change
+ return
+
+
+def __(text):
+ text.value = ""
+ return
+
+
+def __(text):
+ text.on_change = ""
+ return
+
+
+if __name__ == "__main__":
+ app.run()