Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add of_type to _evaluate #4051

Merged
merged 2 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading