From 61e503c4d13f772bb13e42e946df509c2663db9f Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 5 Dec 2024 19:52:17 +0100 Subject: [PATCH] only implement changed check for ComputedVar, put it in has_changed method --- reflex/state.py | 11 ++++------- reflex/vars/base.py | 19 ++++++++++++------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/reflex/state.py b/reflex/state.py index 4c6e8fec6..b2f9f5e01 100644 --- a/reflex/state.py +++ b/reflex/state.py @@ -1288,8 +1288,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): return if name in self.backend_vars: - if self._backend_vars.get(name) == value: - return self._backend_vars.__setitem__(name, value) self.dirty_vars.add(name) self._mark_dirty() @@ -1325,9 +1323,6 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): ) # Set the attribute. - current_value = getattr(self, name, None) - if current_value == value: - return super().__setattr__(name, value) # Add the var to the dirty list. @@ -1831,8 +1826,10 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow): for cvar in self._dirty_computed_vars(from_vars=calc_vars): actual_var = self.computed_vars.get(cvar) if actual_var is not None: - changed = actual_var.mark_dirty(instance=self) - if not changed: + if actual_var.has_changed(instance=self): + actual_var.mark_dirty(instance=self) + else: + # var has not changed, do not mark as dirty continue self.dirty_vars.add(cvar) dirty_vars.add(cvar) diff --git a/reflex/vars/base.py b/reflex/vars/base.py index 8444a29d0..1c14dc9e1 100644 --- a/reflex/vars/base.py +++ b/reflex/vars/base.py @@ -2158,22 +2158,27 @@ class ComputedVar(Var[RETURN_TYPE]): self_is_top_of_stack = False return d - def mark_dirty(self, instance: BaseState) -> bool: + def mark_dirty(self, instance: BaseState) -> None: """Mark this ComputedVar as dirty. + Args: + instance: the state instance that needs to recompute the value. + """ + with contextlib.suppress(AttributeError): + delattr(instance, self._cache_attr) + + def has_changed(self, instance: BaseState) -> bool: + """Check if the ComputedVar value has changed. + Args: instance: the state instance that needs to recompute the value. Returns: - True if the value was marked dirty (has changed), False otherwise. + True if the value has changed, False otherwise. """ cached_value = getattr(instance, self._cache_attr, None) new_value = self.fget(instance) - if cached_value == new_value: - return False - with contextlib.suppress(AttributeError): - delattr(instance, self._cache_attr) - return True + return cached_value != new_value def _determine_var_type(self) -> Type: """Get the type of the var.