Skip to content

Commit

Permalink
add of_type to _evaluate (#4051)
Browse files Browse the repository at this point in the history
* add of_type to _evaluate

* get it right pyright
  • Loading branch information
adhami3310 authored and simon committed Oct 23, 2024
1 parent 1ce0016 commit ec8aecf
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
20 changes: 16 additions & 4 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,26 +699,38 @@ def _item_is_event_handler(name: str, value: Any) -> bool:
)

@classmethod
def _evaluate(cls, f: Callable[[Self], Any]) -> Var:
def _evaluate(
cls, f: Callable[[Self], Any], of_type: Union[type, None] = None
) -> Var:
"""Evaluate a function to a ComputedVar. Experimental.
Args:
f: The function to evaluate.
of_type: The type of the ComputedVar. Defaults to Component.
Returns:
The ComputedVar.
"""
console.warn(
"The _evaluate method is experimental and may be removed in future versions."
)
from reflex.components.base.fragment import fragment
from reflex.components.component import Component

of_type = of_type or Component

unique_var_name = get_unique_variable_name()

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

if not isinstance(result, of_type):
console.warn(
f"Inline ComputedVar {f} expected type {of_type}, got {type(result)}. "
"You can specify expected type with `of_type` argument."
)

return result

setattr(cls, unique_var_name, computed_var_func)
cls.computed_vars[unique_var_name] = computed_var_func
Expand Down
4 changes: 3 additions & 1 deletion tests/integration/test_dynamic_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ def index():
DynamicComponentsState.client_token_component,
DynamicComponentsState.button,
rx.text(
DynamicComponentsState._evaluate(lambda state: factorial(state.value)),
DynamicComponentsState._evaluate(
lambda state: factorial(state.value), of_type=int
),
id="factorial",
),
)
Expand Down

0 comments on commit ec8aecf

Please sign in to comment.