Skip to content

Commit

Permalink
make it faster
Browse files Browse the repository at this point in the history
  • Loading branch information
adhami3310 committed Feb 7, 2025
1 parent 773969a commit e3e983a
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 8 deletions.
13 changes: 12 additions & 1 deletion reflex/components/base/bare.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,23 @@
from reflex.components.tags.tagless import Tagless
from reflex.config import PerformanceMode, environment
from reflex.utils import console
from reflex.utils.decorator import once
from reflex.utils.imports import ParsedImportDict
from reflex.vars import BooleanVar, ObjectVar, Var
from reflex.vars.base import VarData
from reflex.vars.sequence import LiteralStringVar


@once
def performace_mode():
"""Get the performance mode.
Returns:
The performance mode.
"""
return environment.REFLEX_PERF_MODE.get()


def validate_str(value: str):
"""Validate a string value.
Expand All @@ -24,7 +35,7 @@ def validate_str(value: str):
Raises:
ValueError: If the value is a Var and the performance mode is set to raise.
"""
perf_mode = environment.REFLEX_PERF_MODE.get()
perf_mode = performace_mode()
if perf_mode != PerformanceMode.OFF and value.startswith("reflex___state"):
if perf_mode == PerformanceMode.WARN:
console.warn(
Expand Down
25 changes: 25 additions & 0 deletions reflex/utils/decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Decorator utilities."""

from typing import Callable, TypeVar

T = TypeVar("T")


def once(f: Callable[[], T]) -> Callable[[], T]:
"""A decorator that calls the function once and caches the result.
Args:
f: The function to call.
Returns:
A function that calls the function once and caches the result.
"""
unset = object()
value: object | T = unset

def wrapper() -> T:
nonlocal value
value = f() if value is unset else value
return value # pyright: ignore[reportReturnType]

return wrapper
21 changes: 14 additions & 7 deletions tests/units/test_var.py
Original file line number Diff line number Diff line change
Expand Up @@ -1896,18 +1896,25 @@ def test_var_data_with_hooks_value():
assert var_data == VarData(hooks=["what", "whot", "whott"])


def test_str_var_in_components():
from reflex.config import environment

current_performance_mode = environment.REFLEX_PERF_MODE.get()
environment.REFLEX_PERF_MODE.set(PerformanceMode.RAISE)

def test_str_var_in_components(mocker):
class StateWithVar(rx.State):
field: int = 1

mocker.patch(
"reflex.components.base.bare.performace_mode",
lambda: PerformanceMode.RAISE,
)

with pytest.raises(ValueError):
rx.vstack(
str(StateWithVar.field),
)

environment.REFLEX_PERF_MODE.set(current_performance_mode)
mocker.patch(
"reflex.components.base.bare.performace_mode",
lambda: PerformanceMode.OFF,
)

rx.vstack(
str(StateWithVar.field),
)

0 comments on commit e3e983a

Please sign in to comment.