add of_type to _evaluate (#4051)

* add of_type to _evaluate

* get it right pyright
This commit is contained in:
Khaleel Al-Adhami 2024-10-03 13:01:19 -07:00 committed by GitHub
parent 27bb7179d6
commit 56709a210b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 5 deletions

View File

@ -699,11 +699,14 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
)
@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.
@ -711,14 +714,23 @@ class BaseState(Base, ABC, extra=pydantic.Extra.allow):
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

View File

@ -65,7 +65,9 @@ def DynamicComponents():
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",
),
)