Skip to content

Commit

Permalink
implement _evaluate in state
Browse files Browse the repository at this point in the history
  • Loading branch information
adhami3310 committed Sep 27, 2024
1 parent eea5dc1 commit 5e63164
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
33 changes: 31 additions & 2 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
Dict,
List,
Optional,
Self,
Sequence,
Set,
Tuple,
Expand All @@ -42,6 +43,7 @@
Var,
computed_var,
dispatch,
get_unique_variable_name,
is_computed_var,
)

Expand Down Expand Up @@ -77,8 +79,8 @@
from reflex.utils.types import override
from reflex.vars import VarData

if TYPE_CHECKING:
from reflex.components.component import Component
# if TYPE_CHECKING:
# from reflex.components.component import Component


Delta = Dict[str, Any]
Expand Down Expand Up @@ -685,6 +687,33 @@ def _item_is_event_handler(name: str, value: Any) -> bool:
and hasattr(value, "__code__")
)

@classmethod
def _evaluate(cls, f: Callable[[Self], Any]) -> Var:
"""Evaluate a function to a ComputedVar. Experimental.
Args:
f: The function to evaluate.
Returns:
The ComputedVar.
"""
from reflex.components.base.fragment import fragment
from reflex.components.component import Component

unique_var_name = get_unique_variable_name()

@computed_var(_js_expr=unique_var_name, return_type=Component)
def computed_var_func(state: Self):
return fragment(f(state))

setattr(cls, unique_var_name, computed_var_func)
cls.computed_vars[unique_var_name] = computed_var_func
cls.vars[unique_var_name] = computed_var_func
cls._update_substate_inherited_vars({unique_var_name: computed_var_func})
cls._always_dirty_computed_vars.add(unique_var_name)

return getattr(cls, unique_var_name)

@classmethod
def _mixins(cls) -> List[Type]:
"""Get the mixin classes of the state.
Expand Down
5 changes: 3 additions & 2 deletions reflex/vars/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1559,8 +1559,9 @@ def __init__(
Raises:
TypeError: If the computed var dependencies are not Var instances or var names.
"""
hints = get_type_hints(fget)
hint = hints.get("return", Any)
hint = kwargs.pop("return_type", None) or get_type_hints(fget).get(
"return", Any
)

kwargs["_js_expr"] = kwargs.pop("_js_expr", fget.__name__)
kwargs["_var_type"] = kwargs.pop("_var_type", hint)
Expand Down

0 comments on commit 5e63164

Please sign in to comment.