add type validation to computed vars

This commit is contained in:
Khaleel Al-Adhami 2024-10-29 16:45:15 -07:00
parent e1cbce53b5
commit c62b547005

View File

@ -63,7 +63,14 @@ from reflex.utils.imports import (
ParsedImportDict,
parse_imports,
)
from reflex.utils.types import GenericType, Self, get_origin, has_args, unionize
from reflex.utils.types import (
GenericType,
Self,
_isinstance,
get_origin,
has_args,
unionize,
)
if TYPE_CHECKING:
from reflex.state import BaseState
@ -1833,6 +1840,14 @@ class ComputedVar(Var[RETURN_TYPE]):
"return", Any
)
if hint is Any:
console.deprecate(
"untyped-computed-var",
"ComputedVar should have a return type annotation.",
"0.6.5",
"0.7.0",
)
kwargs.setdefault("_js_expr", fget.__name__)
kwargs.setdefault("_var_type", hint)
@ -2026,8 +2041,8 @@ class ComputedVar(Var[RETURN_TYPE]):
)
if not self._cache:
return self.fget(instance)
value = self.fget(instance)
else:
# handle caching
if not hasattr(instance, self._cache_attr) or self.needs_update(instance):
# Set cache attr on state instance.
@ -2036,7 +2051,18 @@ class ComputedVar(Var[RETURN_TYPE]):
instance._was_touched = True
# Set the last updated timestamp on the state instance.
setattr(instance, self._last_updated_attr, datetime.datetime.now())
return getattr(instance, self._cache_attr)
value = getattr(instance, self._cache_attr)
if not _isinstance(value, self._var_type):
console.deprecate(
"mismatched-computed-var-return",
f"Computed var {type(instance).__name__}.{self._js_expr} returned value of type {type(value)}, "
f"expected {self._var_type}. This might cause unexpected behavior.",
"0.6.5",
"0.7.0",
)
return value
def _deps(
self,