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: ui element clone, init with with new instance args (#1939)
Akshay Agrawal7933663597d6
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 3842c1de17..58ade96f1e 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -4,9 +4,10 @@ from __future__ import annotationsimport abcimport base64import copy+import typesimport uuidimport weakref-from dataclasses import dataclass+from dataclasses import dataclass, fieldsfrom typing import (TYPE_CHECKING,Any,@@ -63,6 +64,17 @@ class Lens:key: str+@dataclass+class InitializationArgs(Generic[S, T]):+ component_name: str+ initial_value: S+ label: Optional[str]+ on_change: Optional[Callable[[T], None]]+ args: dict[str, JSONType]+ slotted_html: str+ functions: tuple[Function[Any, Any], ...]++class MarimoConvertValueException(Exception):pass@@ -129,33 +141,43 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):# arguments stored in signature order for cloningself._component_args = args- self._args = (- component_name,- initial_value,- label,- on_change,- args,- slotted_html,- functions,+ self._args: InitializationArgs[S, T] = InitializationArgs(+ component_name=component_name,+ initial_value=initial_value,+ label=label,+ on_change=on_change,+ args=args,+ slotted_html=slotted_html,+ functions=functions,)self._initialized = False- self._initialize(*self._args)+ self._initialize(self._args)self._initialized = Truedef _initialize(- self,- component_name: str,- initial_value: S,- label: Optional[str],- on_change: Optional[Callable[[T], None]],- args: dict[str, JSONType],- slotted_html: str,- functions: tuple[Function[Any, Any], ...] = (),+ self, initialization_args: InitializationArgs[S, T]) -> None:"""Initialize the UIElementSplit out from __init__ so _clone() typechecks"""+ (+ component_name,+ initial_value,+ label,+ on_change,+ args,+ slotted_html,+ functions,+ ) = (+ initialization_args.component_name,+ initialization_args.initial_value,+ initialization_args.label,+ initialization_args.on_change,+ initialization_args.args,+ initialization_args.slotted_html,+ initialization_args.functions,+ )# A UIElement may be a child ("lens") of another UI element.## Set with self._register_as_view() after initialization, since parents@@ -443,8 +465,42 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):setattr(result, k, v)else:setattr(result, k, copy.deepcopy(v, memo))+# Get a new object ID and function namespace- result._initialize(*self._args)+ #+ # We use the new instance's functions, since they are typically bound+ # to the UI element instance. But we only use the new on_change+ # if the old one was bound to self.+ args: InitializationArgs[S, T]+ if (+ isinstance(self._args.on_change, types.MethodType)+ and self._args.on_change.__self__ is self+ ):+ # on_change was bound to self; use the new one.+ args = InitializationArgs(+ **{+ # dataclass asdict does a deepcopy, we want shallow.+ **{+ field.name: getattr(self._args, field.name)+ for field in fields(self._args)+ },+ "on_change": result._args.on_change,+ "functions": result._args.functions,+ }+ )+ else:+ # otherwise, use the original on_change, which may be a state+ # SetFunctor or something else unrelated to this instance.+ args = InitializationArgs(+ **{+ **{+ field.name: getattr(self._args, field.name)+ for field in fields(self._args)+ },+ "functions": result._args.functions,+ }+ )+ result._initialize(args)return resultdef _clone(self) -> UIElement[S, T]:diff --git a/marimo/_smoke_tests/bugs/1927.py b/marimo/_smoke_tests/bugs/1927.pyindex e3d23a67e7..92736d815a 100644--- a/marimo/_smoke_tests/bugs/1927.py+++ b/marimo/_smoke_tests/bugs/1927.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.7.14"diff --git a/marimo/_smoke_tests/bugs/1933.py b/marimo/_smoke_tests/bugs/1933.pynew file mode 100644index 0000000000..58366ffc92--- /dev/null+++ b/marimo/_smoke_tests/bugs/1933.py@@ -0,0 +1,42 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.7.14"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __():+ from vega_datasets import data+ return data,+++def __(data, mo):+ t = mo.ui.table(data.cars())+ return t,+++def __(mo, t):+ dictionary = mo.ui.dictionary({+ "cars": t+ })+ id(dictionary["cars"]), dictionary+ return dictionary,+++def __(dictionary):+ dictionary.value["cars"]+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_core/test_ui_element.py b/tests/_plugins/ui/_core/test_ui_element.pynew file mode 100644index 0000000000..57e1f206ea--- /dev/null+++ b/tests/_plugins/ui/_core/test_ui_element.py@@ -0,0 +1,34 @@+from marimo._plugins.ui._core.ui_element import UIElement+++class Element(UIElement[int, int]):+ _name: str = "element"++ def __init__(self) -> None:+ super().__init__(+ component_name=Element._name,+ initial_value=0,+ label=None,+ args={},+ on_change=self.on_change_method,+ )++ def on_change_method(self, value: int) -> None:+ del value+ ...++ def _convert_value(self, value: int) -> int:+ return value+++def test_ui_element_clone() -> None:+ element = Element()+ clone = element._clone()++ assert element._id != clone._id++ # the on_change method should be bound to the clone instance, not the+ # original instance+ assert element._on_change is not None+ assert clone._on_change is not None+ assert id(element._on_change.__self__) != id(clone._on_change.__self__)