state.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620
  1. """Define the reflex state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import builtins
  5. import contextlib
  6. import copy
  7. import dataclasses
  8. import functools
  9. import inspect
  10. import pickle
  11. import sys
  12. import typing
  13. import warnings
  14. from abc import ABC
  15. from collections.abc import AsyncIterator, Callable, Sequence
  16. from hashlib import md5
  17. from types import FunctionType
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. BinaryIO,
  22. ClassVar,
  23. TypeVar,
  24. cast,
  25. get_args,
  26. get_type_hints,
  27. )
  28. import pydantic.v1 as pydantic
  29. from pydantic import BaseModel as BaseModelV2
  30. from pydantic.v1 import BaseModel as BaseModelV1
  31. from pydantic.v1.fields import ModelField
  32. from rich.markup import escape
  33. from typing_extensions import Self
  34. import reflex.istate.dynamic
  35. from reflex import constants, event
  36. from reflex.base import Base
  37. from reflex.config import PerformanceMode, environment
  38. from reflex.event import (
  39. BACKGROUND_TASK_MARKER,
  40. Event,
  41. EventHandler,
  42. EventSpec,
  43. fix_events,
  44. )
  45. from reflex.istate.data import RouterData
  46. from reflex.istate.proxy import ImmutableMutableProxy as ImmutableMutableProxy
  47. from reflex.istate.proxy import MutableProxy, StateProxy
  48. from reflex.istate.storage import ClientStorageBase
  49. from reflex.model import Model
  50. from reflex.utils import console, format, prerequisites, types
  51. from reflex.utils.exceptions import (
  52. ComputedVarShadowsBaseVarsError,
  53. ComputedVarShadowsStateVarError,
  54. DynamicComponentInvalidSignatureError,
  55. DynamicRouteArgShadowsStateVarError,
  56. EventHandlerShadowsBuiltInStateMethodError,
  57. ReflexRuntimeError,
  58. SetUndefinedStateVarError,
  59. StateMismatchError,
  60. StateSchemaMismatchError,
  61. StateSerializationError,
  62. StateTooLargeError,
  63. UnretrievableVarValueError,
  64. )
  65. from reflex.utils.exceptions import ImmutableStateError as ImmutableStateError
  66. from reflex.utils.exec import is_testing_env
  67. from reflex.utils.types import (
  68. _isinstance,
  69. get_origin,
  70. is_union,
  71. true_type_for_pydantic_field,
  72. value_inside_optional,
  73. )
  74. from reflex.vars import VarData
  75. from reflex.vars.base import (
  76. ComputedVar,
  77. DynamicRouteVar,
  78. Var,
  79. computed_var,
  80. dispatch,
  81. get_unique_variable_name,
  82. is_computed_var,
  83. )
  84. if TYPE_CHECKING:
  85. from reflex.components.component import Component
  86. Delta = dict[str, Any]
  87. var = computed_var
  88. if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF:
  89. # If the state is this large, it's considered a performance issue.
  90. TOO_LARGE_SERIALIZED_STATE = environment.REFLEX_STATE_SIZE_LIMIT.get() * 1024
  91. # Only warn about each state class size once.
  92. _WARNED_ABOUT_STATE_SIZE: set[str] = set()
  93. # Errors caught during pickling of state
  94. HANDLED_PICKLE_ERRORS = (
  95. pickle.PicklingError,
  96. AttributeError,
  97. IndexError,
  98. TypeError,
  99. ValueError,
  100. )
  101. # For BaseState.get_var_value
  102. VAR_TYPE = TypeVar("VAR_TYPE")
  103. def _no_chain_background_task(
  104. state_cls: type[BaseState], name: str, fn: Callable
  105. ) -> Callable:
  106. """Protect against directly chaining a background task from another event handler.
  107. Args:
  108. state_cls: The state class that the event handler is in.
  109. name: The name of the background task.
  110. fn: The background task coroutine function / generator.
  111. Returns:
  112. A compatible coroutine function / generator that raises a runtime error.
  113. Raises:
  114. TypeError: If the background task is not async.
  115. """
  116. call = f"{state_cls.__name__}.{name}"
  117. message = (
  118. f"Cannot directly call background task {name!r}, use "
  119. f"`yield {call}` or `return {call}` instead."
  120. )
  121. if inspect.iscoroutinefunction(fn):
  122. async def _no_chain_background_task_co(*args, **kwargs):
  123. raise RuntimeError(message)
  124. return _no_chain_background_task_co
  125. if inspect.isasyncgenfunction(fn):
  126. async def _no_chain_background_task_gen(*args, **kwargs):
  127. yield
  128. raise RuntimeError(message)
  129. return _no_chain_background_task_gen
  130. raise TypeError(f"{fn} is marked as a background task, but is not async.")
  131. def _substate_key(
  132. token: str,
  133. state_cls_or_name: BaseState | type[BaseState] | str | Sequence[str],
  134. ) -> str:
  135. """Get the substate key.
  136. Args:
  137. token: The token of the state.
  138. state_cls_or_name: The state class/instance or name or sequence of name parts.
  139. Returns:
  140. The substate key.
  141. """
  142. if isinstance(state_cls_or_name, BaseState) or (
  143. isinstance(state_cls_or_name, type) and issubclass(state_cls_or_name, BaseState)
  144. ):
  145. state_cls_or_name = state_cls_or_name.get_full_name()
  146. elif isinstance(state_cls_or_name, (list, tuple)):
  147. state_cls_or_name = ".".join(state_cls_or_name)
  148. return f"{token}_{state_cls_or_name}"
  149. def _split_substate_key(substate_key: str) -> tuple[str, str]:
  150. """Split the substate key into token and state name.
  151. Args:
  152. substate_key: The substate key.
  153. Returns:
  154. Tuple of token and state name.
  155. """
  156. token, _, state_name = substate_key.partition("_")
  157. return token, state_name
  158. @dataclasses.dataclass(frozen=True, init=False)
  159. class EventHandlerSetVar(EventHandler):
  160. """A special event handler to wrap setvar functionality."""
  161. state_cls: type[BaseState] = dataclasses.field(init=False)
  162. def __init__(self, state_cls: type[BaseState]):
  163. """Initialize the EventHandlerSetVar.
  164. Args:
  165. state_cls: The state class that vars will be set on.
  166. """
  167. super().__init__(
  168. fn=type(self).setvar,
  169. state_full_name=state_cls.get_full_name(),
  170. )
  171. object.__setattr__(self, "state_cls", state_cls)
  172. def setvar(self, var_name: str, value: Any):
  173. """Set the state variable to the value of the event.
  174. Note: `self` here will be an instance of the state, not EventHandlerSetVar.
  175. Args:
  176. var_name: The name of the variable to set.
  177. value: The value to set the variable to.
  178. """
  179. getattr(self, constants.SETTER_PREFIX + var_name)(value)
  180. def __call__(self, *args: Any) -> EventSpec:
  181. """Performs pre-checks and munging on the provided args that will become an EventSpec.
  182. Args:
  183. *args: The event args.
  184. Returns:
  185. The (partial) EventSpec that will be used to create the event to setvar.
  186. Raises:
  187. AttributeError: If the given Var name does not exist on the state.
  188. EventHandlerValueError: If the given Var name is not a str
  189. NotImplementedError: If the setter for the given Var is async
  190. """
  191. from reflex.utils.exceptions import EventHandlerValueError
  192. if args:
  193. if not isinstance(args[0], str):
  194. raise EventHandlerValueError(
  195. f"Var name must be passed as a string, got {args[0]!r}"
  196. )
  197. handler = getattr(self.state_cls, constants.SETTER_PREFIX + args[0], None)
  198. # Check that the requested Var setter exists on the State at compile time.
  199. if handler is None:
  200. raise AttributeError(
  201. f"Variable `{args[0]}` cannot be set on `{self.state_cls.get_full_name()}`"
  202. )
  203. if asyncio.iscoroutinefunction(handler.fn):
  204. raise NotImplementedError(
  205. f"Setter for {args[0]} is async, which is not supported."
  206. )
  207. return super().__call__(*args)
  208. if TYPE_CHECKING:
  209. from pydantic.v1.fields import ModelField
  210. def _unwrap_field_type(type_: types.GenericType) -> type:
  211. """Unwrap rx.Field type annotations.
  212. Args:
  213. type_: The type to unwrap.
  214. Returns:
  215. The unwrapped type.
  216. """
  217. from reflex.vars import Field
  218. if get_origin(type_) is Field:
  219. return get_args(type_)[0]
  220. return type_
  221. def get_var_for_field(cls: type[BaseState], f: ModelField) -> Var:
  222. """Get a Var instance for a Pydantic field.
  223. Args:
  224. cls: The state class.
  225. f: The Pydantic field.
  226. Returns:
  227. The Var instance.
  228. """
  229. field_name = (
  230. format.format_state_name(cls.get_full_name()) + "." + f.name + "_rx_state_"
  231. )
  232. return dispatch(
  233. field_name=field_name,
  234. var_data=VarData.from_state(cls, f.name),
  235. result_var_type=_unwrap_field_type(true_type_for_pydantic_field(f)),
  236. )
  237. async def _resolve_delta(delta: Delta) -> Delta:
  238. """Await all coroutines in the delta.
  239. Args:
  240. delta: The delta to process.
  241. Returns:
  242. The same delta dict with all coroutines resolved to their return value.
  243. """
  244. tasks = {}
  245. for state_name, state_delta in delta.items():
  246. for var_name, value in state_delta.items():
  247. if asyncio.iscoroutine(value):
  248. tasks[state_name, var_name] = asyncio.create_task(value)
  249. for (state_name, var_name), task in tasks.items():
  250. delta[state_name][var_name] = await task
  251. return delta
  252. all_base_state_classes: dict[str, None] = {}
  253. class BaseState(Base, ABC, extra=pydantic.Extra.allow):
  254. """The state of the app."""
  255. # A map from the var name to the var.
  256. vars: ClassVar[builtins.dict[str, Var]] = {}
  257. # The base vars of the class.
  258. base_vars: ClassVar[builtins.dict[str, Var]] = {}
  259. # The computed vars of the class.
  260. computed_vars: ClassVar[builtins.dict[str, ComputedVar]] = {}
  261. # Vars inherited by the parent state.
  262. inherited_vars: ClassVar[builtins.dict[str, Var]] = {}
  263. # Backend base vars that are never sent to the client.
  264. backend_vars: ClassVar[builtins.dict[str, Any]] = {}
  265. # Backend base vars inherited
  266. inherited_backend_vars: ClassVar[builtins.dict[str, Any]] = {}
  267. # The event handlers.
  268. event_handlers: ClassVar[builtins.dict[str, EventHandler]] = {}
  269. # A set of subclassses of this class.
  270. class_subclasses: ClassVar[set[type[BaseState]]] = set()
  271. # Mapping of var name to set of (state_full_name, var_name) that depend on it.
  272. _var_dependencies: ClassVar[builtins.dict[str, set[tuple[str, str]]]] = {}
  273. # Set of vars which always need to be recomputed
  274. _always_dirty_computed_vars: ClassVar[set[str]] = set()
  275. # Set of substates which always need to be recomputed
  276. _always_dirty_substates: ClassVar[set[str]] = set()
  277. # Set of states which might need to be recomputed if vars in this state change.
  278. _potentially_dirty_states: ClassVar[set[str]] = set()
  279. # The parent state.
  280. parent_state: BaseState | None = None
  281. # The substates of the state.
  282. substates: builtins.dict[str, BaseState] = {}
  283. # The set of dirty vars.
  284. dirty_vars: set[str] = set()
  285. # The set of dirty substates.
  286. dirty_substates: set[str] = set()
  287. # The routing path that triggered the state
  288. router_data: builtins.dict[str, Any] = {}
  289. # Per-instance copy of backend base variable values
  290. _backend_vars: builtins.dict[str, Any] = {}
  291. # The router data for the current page
  292. router: RouterData = RouterData()
  293. # Whether the state has ever been touched since instantiation.
  294. _was_touched: bool = False
  295. # Whether this state class is a mixin and should not be instantiated.
  296. _mixin: ClassVar[bool] = False
  297. # A special event handler for setting base vars.
  298. setvar: ClassVar[EventHandler]
  299. def __init__(
  300. self,
  301. parent_state: BaseState | None = None,
  302. init_substates: bool = True,
  303. _reflex_internal_init: bool = False,
  304. **kwargs,
  305. ):
  306. """Initialize the state.
  307. DO NOT INSTANTIATE STATE CLASSES DIRECTLY! Use StateManager.get_state() instead.
  308. Args:
  309. parent_state: The parent state.
  310. init_substates: Whether to initialize the substates in this instance.
  311. _reflex_internal_init: A flag to indicate that the state is being initialized by the framework.
  312. **kwargs: The kwargs to set as attributes on the state.
  313. Raises:
  314. ReflexRuntimeError: If the state is instantiated directly by end user.
  315. """
  316. from reflex.utils.exceptions import ReflexRuntimeError
  317. if not _reflex_internal_init and not is_testing_env():
  318. raise ReflexRuntimeError(
  319. "State classes should not be instantiated directly in a Reflex app. "
  320. "See https://reflex.dev/docs/state/ for further information."
  321. )
  322. if type(self)._mixin:
  323. raise ReflexRuntimeError(
  324. f"{type(self).__name__} is a state mixin and cannot be instantiated directly."
  325. )
  326. kwargs["parent_state"] = parent_state
  327. super().__init__()
  328. for name, value in kwargs.items():
  329. setattr(self, name, value)
  330. # Setup the substates (for memory state manager only).
  331. if init_substates:
  332. for substate in self.get_substates():
  333. self.substates[substate.get_name()] = substate(
  334. parent_state=self,
  335. _reflex_internal_init=True,
  336. )
  337. # Create a fresh copy of the backend variables for this instance
  338. self._backend_vars = copy.deepcopy(self.backend_vars)
  339. def __repr__(self) -> str:
  340. """Get the string representation of the state.
  341. Returns:
  342. The string representation of the state.
  343. """
  344. return f"{type(self).__name__}({self.dict()})"
  345. @classmethod
  346. def _get_computed_vars(cls) -> list[ComputedVar]:
  347. """Helper function to get all computed vars of a instance.
  348. Returns:
  349. A list of computed vars.
  350. """
  351. return [
  352. v
  353. for mixin in [*cls._mixins(), cls]
  354. for name, v in mixin.__dict__.items()
  355. if is_computed_var(v) and name not in cls.inherited_vars
  356. ]
  357. @classmethod
  358. def _validate_module_name(cls) -> None:
  359. """Check if the module name is valid.
  360. Reflex uses ___ as state name module separator.
  361. Raises:
  362. NameError: If the module name is invalid.
  363. """
  364. if "___" in cls.__module__:
  365. raise NameError(
  366. "The module name of a State class cannot contain '___'. "
  367. "Please rename the module."
  368. )
  369. @classmethod
  370. def __init_subclass__(cls, mixin: bool = False, **kwargs):
  371. """Do some magic for the subclass initialization.
  372. Args:
  373. mixin: Whether the subclass is a mixin and should not be initialized.
  374. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  375. Raises:
  376. StateValueError: If a substate class shadows another.
  377. """
  378. from reflex.utils.exceptions import StateValueError
  379. super().__init_subclass__(**kwargs)
  380. cls._mixin = mixin
  381. if mixin:
  382. return
  383. # Handle locally-defined states for pickling.
  384. if "<locals>" in cls.__qualname__:
  385. cls._handle_local_def()
  386. # Validate the module name.
  387. cls._validate_module_name()
  388. # Event handlers should not shadow builtin state methods.
  389. cls._check_overridden_methods()
  390. # Computed vars should not shadow builtin state props.
  391. cls._check_overridden_basevars()
  392. # Reset subclass tracking for this class.
  393. cls.class_subclasses = set()
  394. # Reset dirty substate tracking for this class.
  395. cls._always_dirty_substates = set()
  396. cls._potentially_dirty_states = set()
  397. # Get the parent vars.
  398. parent_state = cls.get_parent_state()
  399. if parent_state is not None:
  400. cls.inherited_vars = parent_state.vars
  401. cls.inherited_backend_vars = parent_state.backend_vars
  402. # Check if another substate class with the same name has already been defined.
  403. if cls.get_name() in {c.get_name() for c in parent_state.class_subclasses}:
  404. # This should not happen, since we have added module prefix to state names in #3214
  405. raise StateValueError(
  406. f"The substate class '{cls.get_name()}' has been defined multiple times. "
  407. "Shadowing substate classes is not allowed."
  408. )
  409. # Track this new subclass in the parent state's subclasses set.
  410. parent_state.class_subclasses.add(cls)
  411. # Get computed vars.
  412. computed_vars = cls._get_computed_vars()
  413. cls._check_overridden_computed_vars()
  414. new_backend_vars = {
  415. name: value
  416. for name, value in cls.__dict__.items()
  417. if types.is_backend_base_variable(name, cls)
  418. }
  419. # Add annotated backend vars that may not have a default value.
  420. new_backend_vars.update(
  421. {
  422. name: cls._get_var_default(name, annotation_value)
  423. for name, annotation_value in cls._get_type_hints().items()
  424. if name not in new_backend_vars
  425. and types.is_backend_base_variable(name, cls)
  426. }
  427. )
  428. cls.backend_vars = {
  429. **cls.inherited_backend_vars,
  430. **new_backend_vars,
  431. }
  432. # Set the base and computed vars.
  433. cls.base_vars = {
  434. f.name: get_var_for_field(cls, f)
  435. for f in cls.get_fields().values()
  436. if f.name not in cls.get_skip_vars()
  437. }
  438. cls.computed_vars = {
  439. v._js_expr: v._replace(merge_var_data=VarData.from_state(cls))
  440. for v in computed_vars
  441. }
  442. cls.vars = {
  443. **cls.inherited_vars,
  444. **cls.base_vars,
  445. **cls.computed_vars,
  446. }
  447. cls.event_handlers = {}
  448. # Setup the base vars at the class level.
  449. for prop in cls.base_vars.values():
  450. cls._init_var(prop)
  451. # Set up the event handlers.
  452. events = {
  453. name: fn
  454. for name, fn in cls.__dict__.items()
  455. if cls._item_is_event_handler(name, fn)
  456. }
  457. for mixin_cls in cls._mixins():
  458. for name, value in mixin_cls.__dict__.items():
  459. if name in cls.inherited_vars:
  460. continue
  461. if is_computed_var(value):
  462. fget = cls._copy_fn(value.fget)
  463. newcv = value._replace(fget=fget, _var_data=VarData.from_state(cls))
  464. # cleanup refs to mixin cls in var_data
  465. setattr(cls, name, newcv)
  466. cls.computed_vars[newcv._js_expr] = newcv
  467. cls.vars[newcv._js_expr] = newcv
  468. continue
  469. if types.is_backend_base_variable(name, mixin_cls):
  470. cls.backend_vars[name] = copy.deepcopy(value)
  471. continue
  472. if events.get(name) is not None:
  473. continue
  474. if not cls._item_is_event_handler(name, value):
  475. continue
  476. if parent_state is not None and parent_state.event_handlers.get(name):
  477. continue
  478. value = cls._copy_fn(value)
  479. value.__qualname__ = f"{cls.__name__}.{name}"
  480. events[name] = value
  481. # Create the setvar event handler for this state
  482. cls._create_setvar()
  483. for name, fn in events.items():
  484. handler = cls._create_event_handler(fn)
  485. cls.event_handlers[name] = handler
  486. setattr(cls, name, handler)
  487. # Initialize per-class var dependency tracking.
  488. cls._var_dependencies = {}
  489. cls._init_var_dependency_dicts()
  490. all_base_state_classes[cls.get_full_name()] = None
  491. @classmethod
  492. def _add_event_handler(
  493. cls,
  494. name: str,
  495. fn: Callable,
  496. ):
  497. """Add an event handler dynamically to the state.
  498. Args:
  499. name: The name of the event handler.
  500. fn: The function to call when the event is triggered.
  501. """
  502. handler = cls._create_event_handler(fn)
  503. cls.event_handlers[name] = handler
  504. setattr(cls, name, handler)
  505. @staticmethod
  506. def _copy_fn(fn: Callable) -> Callable:
  507. """Copy a function. Used to copy ComputedVars and EventHandlers from mixins.
  508. Args:
  509. fn: The function to copy.
  510. Returns:
  511. The copied function.
  512. """
  513. newfn = FunctionType(
  514. fn.__code__,
  515. fn.__globals__,
  516. name=fn.__name__,
  517. argdefs=fn.__defaults__,
  518. closure=fn.__closure__,
  519. )
  520. newfn.__annotations__ = fn.__annotations__
  521. if mark := getattr(fn, BACKGROUND_TASK_MARKER, None):
  522. setattr(newfn, BACKGROUND_TASK_MARKER, mark)
  523. return newfn
  524. @staticmethod
  525. def _item_is_event_handler(name: str, value: Any) -> bool:
  526. """Check if the item is an event handler.
  527. Args:
  528. name: The name of the item.
  529. value: The value of the item.
  530. Returns:
  531. Whether the item is an event handler.
  532. """
  533. return (
  534. not name.startswith("_")
  535. and isinstance(value, Callable)
  536. and not isinstance(value, EventHandler)
  537. and hasattr(value, "__code__")
  538. )
  539. @classmethod
  540. def _evaluate(cls, f: Callable[[Self], Any], of_type: type | None = None) -> Var:
  541. """Evaluate a function to a ComputedVar. Experimental.
  542. Args:
  543. f: The function to evaluate.
  544. of_type: The type of the ComputedVar. Defaults to Component.
  545. Returns:
  546. The ComputedVar.
  547. """
  548. console.warn(
  549. "The _evaluate method is experimental and may be removed in future versions."
  550. )
  551. from reflex.components.component import Component
  552. of_type = of_type or Component
  553. unique_var_name = get_unique_variable_name()
  554. @computed_var(_js_expr=unique_var_name, return_type=of_type)
  555. def computed_var_func(state: Self):
  556. result = f(state)
  557. if not _isinstance(result, of_type, nested=1, treat_var_as_type=False):
  558. console.warn(
  559. f"Inline ComputedVar {f} expected type {escape(str(of_type))}, got {type(result)}. "
  560. "You can specify expected type with `of_type` argument."
  561. )
  562. return result
  563. setattr(cls, unique_var_name, computed_var_func)
  564. cls.computed_vars[unique_var_name] = computed_var_func
  565. cls.vars[unique_var_name] = computed_var_func
  566. cls._update_substate_inherited_vars({unique_var_name: computed_var_func})
  567. cls._always_dirty_computed_vars.add(unique_var_name)
  568. return getattr(cls, unique_var_name)
  569. @classmethod
  570. def _mixins(cls) -> list[type]:
  571. """Get the mixin classes of the state.
  572. Returns:
  573. The mixin classes of the state.
  574. """
  575. return [
  576. mixin
  577. for mixin in cls.__mro__
  578. if (
  579. mixin not in [pydantic.BaseModel, Base, cls]
  580. and issubclass(mixin, BaseState)
  581. and mixin._mixin is True
  582. )
  583. ]
  584. @classmethod
  585. def _handle_local_def(cls):
  586. """Handle locally-defined states for pickling."""
  587. known_names = dir(reflex.istate.dynamic)
  588. proposed_name = cls.__name__
  589. for ix in range(len(known_names)):
  590. if proposed_name not in known_names:
  591. break
  592. proposed_name = f"{cls.__name__}_{ix}"
  593. setattr(reflex.istate.dynamic, proposed_name, cls)
  594. cls.__original_name__ = cls.__name__
  595. cls.__original_module__ = cls.__module__
  596. cls.__name__ = cls.__qualname__ = proposed_name
  597. cls.__module__ = reflex.istate.dynamic.__name__
  598. @classmethod
  599. def _get_type_hints(cls) -> dict[str, Any]:
  600. """Get the type hints for this class.
  601. If the class is dynamic, evaluate the type hints with the original
  602. module in the local namespace.
  603. Returns:
  604. The type hints dict.
  605. """
  606. original_module = getattr(cls, "__original_module__", None)
  607. if original_module is not None:
  608. localns = sys.modules[original_module].__dict__
  609. else:
  610. localns = None
  611. return get_type_hints(cls, localns=localns)
  612. @classmethod
  613. def _init_var_dependency_dicts(cls):
  614. """Initialize the var dependency tracking dicts.
  615. Allows the state to know which vars each ComputedVar depends on and
  616. whether a ComputedVar depends on a var in its parent state.
  617. Additional updates tracking dicts for vars and substates that always
  618. need to be recomputed.
  619. """
  620. for cvar_name, cvar in cls.computed_vars.items():
  621. if not cvar._cache:
  622. # Do not perform dep calculation when cache=False (these are always dirty).
  623. continue
  624. for state_name, dvar_set in cvar._deps(objclass=cls).items():
  625. state_cls = cls.get_root_state().get_class_substate(state_name)
  626. for dvar in dvar_set:
  627. defining_state_cls = state_cls
  628. while dvar in {
  629. *defining_state_cls.inherited_vars,
  630. *defining_state_cls.inherited_backend_vars,
  631. }:
  632. parent_state = defining_state_cls.get_parent_state()
  633. if parent_state is not None:
  634. defining_state_cls = parent_state
  635. defining_state_cls._var_dependencies.setdefault(dvar, set()).add(
  636. (cls.get_full_name(), cvar_name)
  637. )
  638. defining_state_cls._potentially_dirty_states.add(
  639. cls.get_full_name()
  640. )
  641. # ComputedVar with cache=False always need to be recomputed
  642. cls._always_dirty_computed_vars = {
  643. cvar_name
  644. for cvar_name, cvar in cls.computed_vars.items()
  645. if not cvar._cache
  646. }
  647. # Any substate containing a ComputedVar with cache=False always needs to be recomputed
  648. if cls._always_dirty_computed_vars:
  649. # Tell parent classes that this substate has always dirty computed vars
  650. state_name = cls.get_name()
  651. parent_state = cls.get_parent_state()
  652. while parent_state is not None:
  653. parent_state._always_dirty_substates.add(state_name)
  654. state_name, parent_state = (
  655. parent_state.get_name(),
  656. parent_state.get_parent_state(),
  657. )
  658. # Reset cached schema value
  659. cls._to_schema.cache_clear()
  660. @classmethod
  661. def _check_overridden_methods(cls):
  662. """Check for shadow methods and raise error if any.
  663. Raises:
  664. EventHandlerShadowsBuiltInStateMethodError: When an event handler shadows an inbuilt state method.
  665. """
  666. overridden_methods = set()
  667. state_base_functions = cls._get_base_functions()
  668. for name, method in inspect.getmembers(cls, inspect.isfunction):
  669. # Check if the method is overridden and not a dunder method
  670. if (
  671. not name.startswith("__")
  672. and method.__name__ in state_base_functions
  673. and state_base_functions[method.__name__] != method
  674. ):
  675. overridden_methods.add(method.__name__)
  676. for method_name in overridden_methods:
  677. raise EventHandlerShadowsBuiltInStateMethodError(
  678. f"The event handler name `{method_name}` shadows a builtin State method; use a different name instead"
  679. )
  680. @classmethod
  681. def _check_overridden_basevars(cls):
  682. """Check for shadow base vars and raise error if any.
  683. Raises:
  684. ComputedVarShadowsBaseVarsError: When a computed var shadows a base var.
  685. """
  686. for computed_var_ in cls._get_computed_vars():
  687. if computed_var_._js_expr in cls.__annotations__:
  688. raise ComputedVarShadowsBaseVarsError(
  689. f"The computed var name `{computed_var_._js_expr}` shadows a base var in {cls.__module__}.{cls.__name__}; use a different name instead"
  690. )
  691. @classmethod
  692. def _check_overridden_computed_vars(cls) -> None:
  693. """Check for shadow computed vars and raise error if any.
  694. Raises:
  695. ComputedVarShadowsStateVarError: When a computed var shadows another.
  696. """
  697. for name, cv in cls.__dict__.items():
  698. if not is_computed_var(cv):
  699. continue
  700. name = cv._js_expr
  701. if name in cls.inherited_vars or name in cls.inherited_backend_vars:
  702. raise ComputedVarShadowsStateVarError(
  703. f"The computed var name `{cv._js_expr}` shadows a var in {cls.__module__}.{cls.__name__}; use a different name instead"
  704. )
  705. @classmethod
  706. def get_skip_vars(cls) -> set[str]:
  707. """Get the vars to skip when serializing.
  708. Returns:
  709. The vars to skip when serializing.
  710. """
  711. return (
  712. set(cls.inherited_vars)
  713. | {
  714. "parent_state",
  715. "substates",
  716. "dirty_vars",
  717. "dirty_substates",
  718. "router_data",
  719. }
  720. | types.RESERVED_BACKEND_VAR_NAMES
  721. )
  722. @classmethod
  723. @functools.lru_cache
  724. def get_parent_state(cls) -> type[BaseState] | None:
  725. """Get the parent state.
  726. Raises:
  727. ValueError: If more than one parent state is found.
  728. Returns:
  729. The parent state.
  730. """
  731. parent_states = [
  732. base
  733. for base in cls.__bases__
  734. if issubclass(base, BaseState) and base is not BaseState and not base._mixin
  735. ]
  736. if len(parent_states) >= 2:
  737. raise ValueError(f"Only one parent state is allowed {parent_states}.")
  738. # The first non-mixin state in the mro is our parent.
  739. for base in cls.mro()[1:]:
  740. if not issubclass(base, BaseState) or base._mixin:
  741. continue
  742. if base is BaseState:
  743. break
  744. return base
  745. return None # No known parent
  746. @classmethod
  747. @functools.lru_cache
  748. def get_root_state(cls) -> type[BaseState]:
  749. """Get the root state.
  750. Returns:
  751. The root state.
  752. """
  753. parent_state = cls.get_parent_state()
  754. return cls if parent_state is None else parent_state.get_root_state()
  755. @classmethod
  756. def get_substates(cls) -> set[type[BaseState]]:
  757. """Get the substates of the state.
  758. Returns:
  759. The substates of the state.
  760. """
  761. return cls.class_subclasses
  762. @classmethod
  763. @functools.lru_cache
  764. def get_name(cls) -> str:
  765. """Get the name of the state.
  766. Returns:
  767. The name of the state.
  768. """
  769. module = cls.__module__.replace(".", "___")
  770. return format.to_snake_case(f"{module}___{cls.__name__}")
  771. @classmethod
  772. @functools.lru_cache
  773. def get_full_name(cls) -> str:
  774. """Get the full name of the state.
  775. Returns:
  776. The full name of the state.
  777. """
  778. name = cls.get_name()
  779. parent_state = cls.get_parent_state()
  780. if parent_state is not None:
  781. name = ".".join((parent_state.get_full_name(), name))
  782. return name
  783. @classmethod
  784. @functools.lru_cache
  785. def get_class_substate(cls, path: Sequence[str] | str) -> type[BaseState]:
  786. """Get the class substate.
  787. Args:
  788. path: The path to the substate.
  789. Returns:
  790. The class substate.
  791. Raises:
  792. ValueError: If the substate is not found.
  793. """
  794. if isinstance(path, str):
  795. path = tuple(path.split("."))
  796. if len(path) == 0:
  797. return cls
  798. if path[0] == cls.get_name():
  799. if len(path) == 1:
  800. return cls
  801. path = path[1:]
  802. for substate in cls.get_substates():
  803. if path[0] == substate.get_name():
  804. return substate.get_class_substate(path[1:])
  805. raise ValueError(f"Invalid path: {path}")
  806. @classmethod
  807. def get_class_var(cls, path: Sequence[str]) -> Any:
  808. """Get the class var.
  809. Args:
  810. path: The path to the var.
  811. Returns:
  812. The class var.
  813. Raises:
  814. ValueError: If the path is invalid.
  815. """
  816. path, name = path[:-1], path[-1]
  817. substate = cls.get_class_substate(tuple(path))
  818. if not hasattr(substate, name):
  819. raise ValueError(f"Invalid path: {path}")
  820. return getattr(substate, name)
  821. @classmethod
  822. def _init_var(cls, prop: Var):
  823. """Initialize a variable.
  824. Args:
  825. prop: The variable to initialize
  826. Raises:
  827. VarTypeError: if the variable has an incorrect type
  828. """
  829. from reflex.utils.exceptions import VarTypeError
  830. if not types.is_valid_var_type(prop._var_type):
  831. raise VarTypeError(
  832. "State vars must be of a serializable type. "
  833. "Valid types include strings, numbers, booleans, lists, "
  834. "dictionaries, dataclasses, datetime objects, and pydantic models. "
  835. f'Found var "{prop._js_expr}" with type {prop._var_type}.'
  836. )
  837. cls._set_var(prop)
  838. cls._create_setter(prop)
  839. cls._set_default_value(prop)
  840. @classmethod
  841. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  842. """Add dynamically a variable to the State.
  843. The variable added this way can be used in the same way as a variable
  844. defined statically in the model.
  845. Args:
  846. name: The name of the variable
  847. type_: The type of the variable
  848. default_value: The default value of the variable
  849. Raises:
  850. NameError: if a variable of this name already exists
  851. """
  852. if name in cls.__fields__:
  853. raise NameError(
  854. f"The variable '{name}' already exist. Use a different name"
  855. )
  856. # create the variable based on name and type
  857. var = Var(
  858. _js_expr=format.format_state_name(cls.get_full_name())
  859. + "."
  860. + name
  861. + "_rx_state_",
  862. _var_type=type_,
  863. _var_data=VarData.from_state(cls, name),
  864. ).guess_type()
  865. # add the pydantic field dynamically (must be done before _init_var)
  866. cls.add_field(var, default_value)
  867. cls._init_var(var)
  868. # update the internal dicts so the new variable is correctly handled
  869. cls.base_vars.update({name: var})
  870. cls.vars.update({name: var})
  871. # let substates know about the new variable
  872. for substate_class in cls.class_subclasses:
  873. substate_class.vars.setdefault(name, var)
  874. # Reinitialize dependency tracking dicts.
  875. cls._init_var_dependency_dicts()
  876. @classmethod
  877. def _set_var(cls, prop: Var):
  878. """Set the var as a class member.
  879. Args:
  880. prop: The var instance to set.
  881. """
  882. setattr(cls, prop._var_field_name, prop)
  883. @classmethod
  884. def _create_event_handler(cls, fn: Any):
  885. """Create an event handler for the given function.
  886. Args:
  887. fn: The function to create an event handler for.
  888. Returns:
  889. The event handler.
  890. """
  891. return EventHandler(fn=fn, state_full_name=cls.get_full_name())
  892. @classmethod
  893. def _create_setvar(cls):
  894. """Create the setvar method for the state."""
  895. cls.setvar = cls.event_handlers["setvar"] = EventHandlerSetVar(state_cls=cls)
  896. @classmethod
  897. def _create_setter(cls, prop: Var):
  898. """Create a setter for the var.
  899. Args:
  900. prop: The var to create a setter for.
  901. """
  902. setter_name = prop._get_setter_name(include_state=False)
  903. if setter_name not in cls.__dict__:
  904. event_handler = cls._create_event_handler(prop._get_setter())
  905. cls.event_handlers[setter_name] = event_handler
  906. setattr(cls, setter_name, event_handler)
  907. @classmethod
  908. def _set_default_value(cls, prop: Var):
  909. """Set the default value for the var.
  910. Args:
  911. prop: The var to set the default value for.
  912. """
  913. # Get the pydantic field for the var.
  914. field = cls.get_fields()[prop._var_field_name]
  915. if field.required:
  916. default_value = prop._get_default_value()
  917. if default_value is not None:
  918. field.required = False
  919. field.default = default_value
  920. if (
  921. not field.required
  922. and field.default is None
  923. and field.default_factory is None
  924. and not types.is_optional(prop._var_type)
  925. ):
  926. # Ensure frontend uses null coalescing when accessing.
  927. object.__setattr__(prop, "_var_type", prop._var_type | None)
  928. @classmethod
  929. def _get_var_default(cls, name: str, annotation_value: Any) -> Any:
  930. """Get the default value of a (backend) var.
  931. Args:
  932. name: The name of the var.
  933. annotation_value: The annotation value of the var.
  934. Returns:
  935. The default value of the var or None.
  936. """
  937. try:
  938. return getattr(cls, name)
  939. except AttributeError:
  940. try:
  941. return Var("", _var_type=annotation_value)._get_default_value()
  942. except TypeError:
  943. pass
  944. return None
  945. @staticmethod
  946. def _get_base_functions() -> dict[str, FunctionType]:
  947. """Get all functions of the state class excluding dunder methods.
  948. Returns:
  949. The functions of rx.State class as a dict.
  950. """
  951. return {
  952. func[0]: func[1]
  953. for func in inspect.getmembers(BaseState, predicate=inspect.isfunction)
  954. if not func[0].startswith("__")
  955. }
  956. @classmethod
  957. def _update_substate_inherited_vars(cls, vars_to_add: dict[str, Var]):
  958. """Update the inherited vars of substates recursively when new vars are added.
  959. Also updates the var dependency tracking dicts after adding vars.
  960. Args:
  961. vars_to_add: names to Var instances to add to substates
  962. """
  963. for substate_class in cls.class_subclasses:
  964. for name, var in vars_to_add.items():
  965. if types.is_backend_base_variable(name, cls):
  966. substate_class.backend_vars.setdefault(name, var)
  967. substate_class.inherited_backend_vars.setdefault(name, var)
  968. else:
  969. substate_class.vars.setdefault(name, var)
  970. substate_class.inherited_vars.setdefault(name, var)
  971. substate_class._update_substate_inherited_vars(vars_to_add)
  972. # Reinitialize dependency tracking dicts.
  973. cls._init_var_dependency_dicts()
  974. @classmethod
  975. def setup_dynamic_args(cls, args: dict[str, str]):
  976. """Set up args for easy access in renderer.
  977. Args:
  978. args: a dict of args
  979. """
  980. if not args:
  981. return
  982. cls._check_overwritten_dynamic_args(list(args.keys()))
  983. def argsingle_factory(param: str):
  984. def inner_func(self: BaseState) -> str:
  985. return self.router.page.params.get(param, "")
  986. return inner_func
  987. def arglist_factory(param: str):
  988. def inner_func(self: BaseState) -> list[str]:
  989. return self.router.page.params.get(param, [])
  990. return inner_func
  991. dynamic_vars = {}
  992. for param, value in args.items():
  993. if value == constants.RouteArgType.SINGLE:
  994. func = argsingle_factory(param)
  995. elif value == constants.RouteArgType.LIST:
  996. func = arglist_factory(param)
  997. else:
  998. continue
  999. dynamic_vars[param] = DynamicRouteVar(
  1000. fget=func,
  1001. auto_deps=False,
  1002. deps=["router"],
  1003. _js_expr=param,
  1004. _var_data=VarData.from_state(cls),
  1005. )
  1006. setattr(cls, param, dynamic_vars[param])
  1007. # Update tracking dicts.
  1008. cls.computed_vars.update(dynamic_vars)
  1009. cls.vars.update(dynamic_vars)
  1010. cls._update_substate_inherited_vars(dynamic_vars)
  1011. @classmethod
  1012. def _check_overwritten_dynamic_args(cls, args: list[str]):
  1013. """Check if dynamic args are shadowing existing vars. Recursively checks all child states.
  1014. Args:
  1015. args: a dict of args
  1016. Raises:
  1017. DynamicRouteArgShadowsStateVarError: If a dynamic arg is shadowing an existing var.
  1018. """
  1019. for arg in args:
  1020. if (
  1021. arg in cls.computed_vars
  1022. and not isinstance(cls.computed_vars[arg], DynamicRouteVar)
  1023. ) or arg in cls.base_vars:
  1024. raise DynamicRouteArgShadowsStateVarError(
  1025. f"Dynamic route arg '{arg}' is shadowing an existing var in {cls.__module__}.{cls.__name__}"
  1026. )
  1027. for substate in cls.get_substates():
  1028. substate._check_overwritten_dynamic_args(args)
  1029. def __getattribute__(self, name: str) -> Any:
  1030. """Get the state var.
  1031. If the var is inherited, get the var from the parent state.
  1032. Args:
  1033. name: The name of the var.
  1034. Returns:
  1035. The value of the var.
  1036. """
  1037. # If the state hasn't been initialized yet, return the default value.
  1038. if not super().__getattribute__("__dict__"):
  1039. return super().__getattribute__(name)
  1040. # Fast path for dunder
  1041. if name.startswith("__"):
  1042. return super().__getattribute__(name)
  1043. # For now, handle router_data updates as a special case.
  1044. if (
  1045. name == constants.ROUTER_DATA
  1046. or name in super().__getattribute__("inherited_vars")
  1047. or name in super().__getattribute__("inherited_backend_vars")
  1048. ):
  1049. parent_state = super().__getattribute__("parent_state")
  1050. if parent_state is not None:
  1051. return getattr(parent_state, name)
  1052. # Allow event handlers to be called on the instance directly.
  1053. event_handlers = super().__getattribute__("event_handlers")
  1054. if name in event_handlers:
  1055. handler = event_handlers[name]
  1056. if handler.is_background:
  1057. fn = _no_chain_background_task(type(self), name, handler.fn)
  1058. else:
  1059. fn = functools.partial(handler.fn, self)
  1060. fn.__module__ = handler.fn.__module__
  1061. fn.__qualname__ = handler.fn.__qualname__
  1062. return fn
  1063. backend_vars = super().__getattribute__("_backend_vars")
  1064. if name in backend_vars:
  1065. value = backend_vars[name]
  1066. else:
  1067. value = super().__getattribute__(name)
  1068. if isinstance(value, EventHandler):
  1069. # The event handler is inherited from a parent, so let the parent convert
  1070. # it to a callable function.
  1071. parent_state = super().__getattribute__("parent_state")
  1072. if parent_state is not None:
  1073. return getattr(parent_state, name)
  1074. if MutableProxy._is_mutable_type(value) and (
  1075. name in super().__getattribute__("base_vars") or name in backend_vars
  1076. ):
  1077. # track changes in mutable containers (list, dict, set, etc)
  1078. return MutableProxy(wrapped=value, state=self, field_name=name)
  1079. return value
  1080. def __setattr__(self, name: str, value: Any):
  1081. """Set the attribute.
  1082. If the attribute is inherited, set the attribute on the parent state.
  1083. Args:
  1084. name: The name of the attribute.
  1085. value: The value of the attribute.
  1086. Raises:
  1087. SetUndefinedStateVarError: If a value of a var is set without first defining it.
  1088. """
  1089. if isinstance(value, MutableProxy):
  1090. # unwrap proxy objects when assigning back to the state
  1091. value = value.__wrapped__
  1092. # Set the var on the parent state.
  1093. if name in self.inherited_vars or name in self.inherited_backend_vars:
  1094. setattr(self.parent_state, name, value)
  1095. return
  1096. if name in self.backend_vars:
  1097. self._backend_vars.__setitem__(name, value)
  1098. self.dirty_vars.add(name)
  1099. self._mark_dirty()
  1100. return
  1101. if (
  1102. name not in self.vars
  1103. and name not in self.get_skip_vars()
  1104. and not name.startswith("__")
  1105. and not name.startswith(
  1106. f"_{getattr(type(self), '__original_name__', type(self).__name__)}__"
  1107. )
  1108. ):
  1109. raise SetUndefinedStateVarError(
  1110. f"The state variable '{name}' has not been defined in '{type(self).__name__}'. "
  1111. f"All state variables must be declared before they can be set."
  1112. )
  1113. fields = self.get_fields()
  1114. if name in fields:
  1115. field = fields[name]
  1116. field_type = _unwrap_field_type(true_type_for_pydantic_field(field))
  1117. if not _isinstance(value, field_type, nested=1, treat_var_as_type=False):
  1118. console.error(
  1119. f"Expected field '{type(self).__name__}.{name}' to receive type '{escape(str(field_type))}',"
  1120. f" but got '{value}' of type '{type(value)}'."
  1121. )
  1122. # Set the attribute.
  1123. super().__setattr__(name, value)
  1124. # Add the var to the dirty list.
  1125. if name in self.base_vars:
  1126. self.dirty_vars.add(name)
  1127. self._mark_dirty()
  1128. # For now, handle router_data updates as a special case
  1129. if name == constants.ROUTER_DATA:
  1130. self.dirty_vars.add(name)
  1131. self._mark_dirty()
  1132. def reset(self):
  1133. """Reset all the base vars to their default values."""
  1134. # Reset the base vars.
  1135. fields = self.get_fields()
  1136. for prop_name in self.base_vars:
  1137. if prop_name == constants.ROUTER:
  1138. continue # never reset the router data
  1139. field = fields[prop_name]
  1140. if default_factory := field.default_factory:
  1141. default = default_factory()
  1142. else:
  1143. default = copy.deepcopy(field.default)
  1144. setattr(self, prop_name, default)
  1145. # Reset the backend vars.
  1146. for prop_name, value in self.backend_vars.items():
  1147. setattr(self, prop_name, copy.deepcopy(value))
  1148. # Recursively reset the substates.
  1149. for substate in self.substates.values():
  1150. substate.reset()
  1151. def _reset_client_storage(self):
  1152. """Reset client storage base vars to their default values."""
  1153. # Client-side storage is reset during hydrate so that clearing cookies
  1154. # on the browser also resets the values on the backend.
  1155. fields = self.get_fields()
  1156. for prop_name in self.base_vars:
  1157. field = fields[prop_name]
  1158. if isinstance(field.default, ClientStorageBase) or (
  1159. isinstance(field.type_, type)
  1160. and issubclass(field.type_, ClientStorageBase)
  1161. ):
  1162. setattr(self, prop_name, copy.deepcopy(field.default))
  1163. # Recursively reset the substate client storage.
  1164. for substate in self.substates.values():
  1165. substate._reset_client_storage()
  1166. def get_substate(self, path: Sequence[str]) -> BaseState:
  1167. """Get the substate.
  1168. Args:
  1169. path: The path to the substate.
  1170. Returns:
  1171. The substate.
  1172. Raises:
  1173. ValueError: If the substate is not found.
  1174. """
  1175. if len(path) == 0:
  1176. return self
  1177. if path[0] == self.get_name():
  1178. if len(path) == 1:
  1179. return self
  1180. path = path[1:]
  1181. if path[0] not in self.substates:
  1182. raise ValueError(f"Invalid path: {path}")
  1183. return self.substates[path[0]].get_substate(path[1:])
  1184. @classmethod
  1185. def _get_potentially_dirty_states(cls) -> set[type[BaseState]]:
  1186. """Get substates which may have dirty vars due to dependencies.
  1187. Returns:
  1188. The set of potentially dirty substate classes.
  1189. """
  1190. return {
  1191. cls.get_class_substate(substate_name)
  1192. for substate_name in cls._always_dirty_substates
  1193. }.union(
  1194. {
  1195. cls.get_root_state().get_class_substate(substate_name)
  1196. for substate_name in cls._potentially_dirty_states
  1197. }
  1198. )
  1199. def _get_root_state(self) -> BaseState:
  1200. """Get the root state of the state tree.
  1201. Returns:
  1202. The root state of the state tree.
  1203. """
  1204. parent_state = self
  1205. while parent_state.parent_state is not None:
  1206. parent_state = parent_state.parent_state
  1207. return parent_state
  1208. async def _get_state_from_redis(self, state_cls: type[T_STATE]) -> T_STATE:
  1209. """Get a state instance from redis.
  1210. Args:
  1211. state_cls: The class of the state.
  1212. Returns:
  1213. The instance of state_cls associated with this state's client_token.
  1214. Raises:
  1215. RuntimeError: If redis is not used in this backend process.
  1216. StateMismatchError: If the state instance is not of the expected type.
  1217. """
  1218. # Then get the target state and all its substates.
  1219. state_manager = get_state_manager()
  1220. if not isinstance(state_manager, StateManagerRedis):
  1221. raise RuntimeError(
  1222. f"Requested state {state_cls.get_full_name()} is not cached and cannot be accessed without redis. "
  1223. "(All states should already be available -- this is likely a bug).",
  1224. )
  1225. state_in_redis = await state_manager.get_state(
  1226. token=_substate_key(self.router.session.client_token, state_cls),
  1227. top_level=False,
  1228. for_state_instance=self,
  1229. )
  1230. if not isinstance(state_in_redis, state_cls):
  1231. raise StateMismatchError(
  1232. f"Searched for state {state_cls.get_full_name()} but found {state_in_redis}."
  1233. )
  1234. return state_in_redis
  1235. def _get_state_from_cache(self, state_cls: type[T_STATE]) -> T_STATE:
  1236. """Get a state instance from the cache.
  1237. Args:
  1238. state_cls: The class of the state.
  1239. Returns:
  1240. The instance of state_cls associated with this state's client_token.
  1241. Raises:
  1242. StateMismatchError: If the state instance is not of the expected type.
  1243. """
  1244. root_state = self._get_root_state()
  1245. substate = root_state.get_substate(state_cls.get_full_name().split("."))
  1246. if not isinstance(substate, state_cls):
  1247. raise StateMismatchError(
  1248. f"Searched for state {state_cls.get_full_name()} but found {substate}."
  1249. )
  1250. return substate
  1251. async def get_state(self, state_cls: type[T_STATE]) -> T_STATE:
  1252. """Get an instance of the state associated with this token.
  1253. Allows for arbitrary access to sibling states from within an event handler.
  1254. Args:
  1255. state_cls: The class of the state.
  1256. Returns:
  1257. The instance of state_cls associated with this state's client_token.
  1258. """
  1259. # Fast case - if this state instance is already cached, get_substate from root state.
  1260. try:
  1261. return self._get_state_from_cache(state_cls)
  1262. except ValueError:
  1263. pass
  1264. # Slow case - fetch missing parent states from redis.
  1265. return await self._get_state_from_redis(state_cls)
  1266. async def get_var_value(self, var: Var[VAR_TYPE]) -> VAR_TYPE:
  1267. """Get the value of an rx.Var from another state.
  1268. Args:
  1269. var: The var to get the value for.
  1270. Returns:
  1271. The value of the var.
  1272. Raises:
  1273. UnretrievableVarValueError: If the var does not have a literal value
  1274. or associated state.
  1275. """
  1276. # Oopsie case: you didn't give me a Var... so get what you give.
  1277. if not isinstance(var, Var):
  1278. return var
  1279. unset = object()
  1280. # Fast case: this is a literal var and the value is known.
  1281. if (
  1282. var_value := getattr(var, "_var_value", unset)
  1283. ) is not unset and not isinstance(var_value, Var):
  1284. return var_value # pyright: ignore [reportReturnType]
  1285. var_data = var._get_all_var_data()
  1286. if var_data is None or not var_data.state:
  1287. raise UnretrievableVarValueError(
  1288. f"Unable to retrieve value for {var._js_expr}: not associated with any state."
  1289. )
  1290. # Fastish case: this var belongs to this state
  1291. if var_data.state == self.get_full_name():
  1292. return getattr(self, var_data.field_name)
  1293. # Slow case: this var belongs to another state
  1294. other_state = await self.get_state(
  1295. self._get_root_state().get_class_substate(var_data.state)
  1296. )
  1297. return getattr(other_state, var_data.field_name)
  1298. def _get_event_handler(
  1299. self, event: Event
  1300. ) -> tuple[BaseState | StateProxy, EventHandler]:
  1301. """Get the event handler for the given event.
  1302. Args:
  1303. event: The event to get the handler for.
  1304. Returns:
  1305. The event handler.
  1306. Raises:
  1307. ValueError: If the event handler or substate is not found.
  1308. """
  1309. # Get the event handler.
  1310. path = event.name.split(".")
  1311. path, name = path[:-1], path[-1]
  1312. substate = self.get_substate(path)
  1313. if not substate:
  1314. raise ValueError(
  1315. "The value of state cannot be None when processing an event."
  1316. )
  1317. handler = substate.event_handlers[name]
  1318. # For background tasks, proxy the state
  1319. if handler.is_background:
  1320. substate = StateProxy(substate)
  1321. return substate, handler
  1322. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  1323. """Obtain event info and process event.
  1324. Args:
  1325. event: The event to process.
  1326. Yields:
  1327. The state update after processing the event.
  1328. """
  1329. # Get the event handler.
  1330. substate, handler = self._get_event_handler(event)
  1331. # Run the event generator and yield state updates.
  1332. async for update in self._process_event(
  1333. handler=handler,
  1334. state=substate,
  1335. payload=event.payload,
  1336. ):
  1337. yield update
  1338. def _check_valid(self, handler: EventHandler, events: Any) -> Any:
  1339. """Check if the events yielded are valid. They must be EventHandlers or EventSpecs.
  1340. Args:
  1341. handler: EventHandler.
  1342. events: The events to be checked.
  1343. Raises:
  1344. TypeError: If any of the events are not valid.
  1345. Returns:
  1346. The events as they are if valid.
  1347. """
  1348. def _is_valid_type(events: Any) -> bool:
  1349. return isinstance(events, (Event, EventHandler, EventSpec))
  1350. if events is None or _is_valid_type(events):
  1351. return events
  1352. if not isinstance(events, Sequence):
  1353. events = [events]
  1354. try:
  1355. if all(_is_valid_type(e) for e in events):
  1356. return events
  1357. except TypeError:
  1358. pass
  1359. coroutines = [e for e in events if asyncio.iscoroutine(e)]
  1360. for coroutine in coroutines:
  1361. coroutine_name = coroutine.__qualname__
  1362. warnings.filterwarnings(
  1363. "ignore", message=f"coroutine '{coroutine_name}' was never awaited"
  1364. )
  1365. raise TypeError(
  1366. f"Your handler {handler.fn.__qualname__} must only return/yield: None, Events or other EventHandlers referenced by their class (i.e. using `type(self)` or other class references)."
  1367. f" Returned events of types {', '.join(map(str, map(type, events)))!s}."
  1368. )
  1369. async def _as_state_update(
  1370. self,
  1371. handler: EventHandler,
  1372. events: EventSpec | list[EventSpec] | None,
  1373. final: bool,
  1374. ) -> StateUpdate:
  1375. """Convert the events to a StateUpdate.
  1376. Fixes the events and checks for validity before converting.
  1377. Args:
  1378. handler: The handler where the events originated from.
  1379. events: The events to queue with the update.
  1380. final: Whether the handler is done processing.
  1381. Returns:
  1382. The valid StateUpdate containing the events and final flag.
  1383. """
  1384. # get the delta from the root of the state tree
  1385. state = self._get_root_state()
  1386. token = self.router.session.client_token
  1387. # Convert valid EventHandler and EventSpec into Event
  1388. fixed_events = fix_events(self._check_valid(handler, events), token)
  1389. try:
  1390. # Get the delta after processing the event.
  1391. delta = await state._get_resolved_delta()
  1392. state._clean()
  1393. return StateUpdate(
  1394. delta=delta,
  1395. events=fixed_events,
  1396. final=final if not handler.is_background else True,
  1397. )
  1398. except Exception as ex:
  1399. state._clean()
  1400. event_specs = (
  1401. prerequisites.get_and_validate_app().app.backend_exception_handler(ex)
  1402. )
  1403. if event_specs is None:
  1404. return StateUpdate()
  1405. event_specs_correct_type = cast(
  1406. list[EventSpec | EventHandler] | None,
  1407. [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
  1408. )
  1409. fixed_events = fix_events(
  1410. event_specs_correct_type,
  1411. token,
  1412. router_data=state.router_data,
  1413. )
  1414. return StateUpdate(
  1415. events=fixed_events,
  1416. final=True,
  1417. )
  1418. async def _process_event(
  1419. self,
  1420. handler: EventHandler,
  1421. state: BaseState | StateProxy,
  1422. payload: builtins.dict,
  1423. ) -> AsyncIterator[StateUpdate]:
  1424. """Process event.
  1425. Args:
  1426. handler: EventHandler to process.
  1427. state: State to process the handler.
  1428. payload: The event payload.
  1429. Yields:
  1430. StateUpdate object
  1431. Raises:
  1432. ValueError: If a string value is received for an int or float type and cannot be converted.
  1433. """
  1434. from reflex.utils import telemetry
  1435. # Get the function to process the event.
  1436. fn = functools.partial(handler.fn, state)
  1437. try:
  1438. type_hints = typing.get_type_hints(handler.fn)
  1439. except Exception:
  1440. type_hints = {}
  1441. for arg, value in list(payload.items()):
  1442. hinted_args = type_hints.get(arg, Any)
  1443. if hinted_args is Any:
  1444. continue
  1445. if is_union(hinted_args):
  1446. if value is None:
  1447. continue
  1448. hinted_args = value_inside_optional(hinted_args)
  1449. if (
  1450. isinstance(value, dict)
  1451. and inspect.isclass(hinted_args)
  1452. and not types.is_generic_alias(hinted_args) # py3.10
  1453. ):
  1454. if issubclass(hinted_args, Model):
  1455. # Remove non-fields from the payload
  1456. payload[arg] = hinted_args(
  1457. **{
  1458. key: value
  1459. for key, value in value.items()
  1460. if key in hinted_args.__fields__
  1461. }
  1462. )
  1463. elif dataclasses.is_dataclass(hinted_args) or issubclass(
  1464. hinted_args, (Base, BaseModelV1, BaseModelV2)
  1465. ):
  1466. payload[arg] = hinted_args(**value)
  1467. elif isinstance(value, list) and (hinted_args is set or hinted_args is set):
  1468. payload[arg] = set(value)
  1469. elif isinstance(value, list) and (
  1470. hinted_args is tuple or hinted_args is tuple
  1471. ):
  1472. payload[arg] = tuple(value)
  1473. elif isinstance(value, str) and (
  1474. hinted_args is int or hinted_args is float
  1475. ):
  1476. try:
  1477. payload[arg] = hinted_args(value)
  1478. except ValueError:
  1479. raise ValueError(
  1480. f"Received a string value ({value}) for {arg} but expected a {hinted_args}"
  1481. ) from None
  1482. else:
  1483. console.warn(
  1484. f"Received a string value ({value}) for {arg} but expected a {hinted_args}. A simple conversion was successful."
  1485. )
  1486. # Wrap the function in a try/except block.
  1487. try:
  1488. # Handle async functions.
  1489. if asyncio.iscoroutinefunction(fn.func):
  1490. events = await fn(**payload)
  1491. # Handle regular functions.
  1492. else:
  1493. events = fn(**payload)
  1494. # Handle async generators.
  1495. if inspect.isasyncgen(events):
  1496. async for event in events:
  1497. yield await state._as_state_update(handler, event, final=False)
  1498. yield await state._as_state_update(handler, events=None, final=True)
  1499. # Handle regular generators.
  1500. elif inspect.isgenerator(events):
  1501. try:
  1502. while True:
  1503. yield await state._as_state_update(
  1504. handler, next(events), final=False
  1505. )
  1506. except StopIteration as si:
  1507. # the "return" value of the generator is not available
  1508. # in the loop, we must catch StopIteration to access it
  1509. if si.value is not None:
  1510. yield await state._as_state_update(
  1511. handler, si.value, final=False
  1512. )
  1513. yield await state._as_state_update(handler, events=None, final=True)
  1514. # Handle regular event chains.
  1515. else:
  1516. yield await state._as_state_update(handler, events, final=True)
  1517. # If an error occurs, throw a window alert.
  1518. except Exception as ex:
  1519. telemetry.send_error(ex, context="backend")
  1520. event_specs = (
  1521. prerequisites.get_and_validate_app().app.backend_exception_handler(ex)
  1522. )
  1523. yield await state._as_state_update(
  1524. handler,
  1525. event_specs,
  1526. final=True,
  1527. )
  1528. def _mark_dirty_computed_vars(self) -> None:
  1529. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  1530. # Append expired computed vars to dirty_vars to trigger recalculation
  1531. self.dirty_vars.update(self._expired_computed_vars())
  1532. # Append always dirty computed vars to dirty_vars to trigger recalculation
  1533. self.dirty_vars.update(self._always_dirty_computed_vars)
  1534. dirty_vars = self.dirty_vars
  1535. while dirty_vars:
  1536. calc_vars, dirty_vars = dirty_vars, set()
  1537. for state_name, cvar in self._dirty_computed_vars(from_vars=calc_vars):
  1538. if state_name == self.get_full_name():
  1539. defining_state = self
  1540. else:
  1541. defining_state = self._get_root_state().get_substate(
  1542. tuple(state_name.split("."))
  1543. )
  1544. defining_state.dirty_vars.add(cvar)
  1545. actual_var = defining_state.computed_vars.get(cvar)
  1546. if actual_var is not None:
  1547. actual_var.mark_dirty(instance=defining_state)
  1548. if defining_state is self:
  1549. dirty_vars.add(cvar)
  1550. else:
  1551. # mark dirty where this var is defined
  1552. defining_state._mark_dirty()
  1553. def _expired_computed_vars(self) -> set[str]:
  1554. """Determine ComputedVars that need to be recalculated based on the expiration time.
  1555. Returns:
  1556. Set of computed vars to include in the delta.
  1557. """
  1558. return {
  1559. cvar
  1560. for cvar in self.computed_vars
  1561. if self.computed_vars[cvar].needs_update(instance=self)
  1562. }
  1563. def _dirty_computed_vars(
  1564. self, from_vars: set[str] | None = None, include_backend: bool = True
  1565. ) -> set[tuple[str, str]]:
  1566. """Determine ComputedVars that need to be recalculated based on the given vars.
  1567. Args:
  1568. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  1569. include_backend: whether to include backend vars in the calculation.
  1570. Returns:
  1571. Set of computed vars to include in the delta.
  1572. """
  1573. return {
  1574. (state_name, cvar)
  1575. for dirty_var in from_vars or self.dirty_vars
  1576. for state_name, cvar in self._var_dependencies.get(dirty_var, set())
  1577. if include_backend or not self.computed_vars[cvar]._backend
  1578. }
  1579. def get_delta(self) -> Delta:
  1580. """Get the delta for the state.
  1581. Returns:
  1582. The delta for the state.
  1583. """
  1584. delta = {}
  1585. self._mark_dirty_computed_vars()
  1586. frontend_computed_vars: set[str] = {
  1587. name for name, cv in self.computed_vars.items() if not cv._backend
  1588. }
  1589. # Return the dirty vars for this instance, any cached/dependent computed vars,
  1590. # and always dirty computed vars (cache=False)
  1591. delta_vars = self.dirty_vars.intersection(self.base_vars).union(
  1592. self.dirty_vars.intersection(frontend_computed_vars)
  1593. )
  1594. subdelta: dict[str, Any] = {
  1595. prop: self.get_value(prop)
  1596. for prop in delta_vars
  1597. if not types.is_backend_base_variable(prop, type(self))
  1598. }
  1599. if len(subdelta) > 0:
  1600. delta[self.get_full_name()] = subdelta
  1601. # Recursively find the substate deltas.
  1602. substates = self.substates
  1603. for substate in self.dirty_substates.union(self._always_dirty_substates):
  1604. delta.update(substates[substate].get_delta())
  1605. # Return the delta.
  1606. return delta
  1607. async def _get_resolved_delta(self) -> Delta:
  1608. """Get the delta for the state after resolving all coroutines.
  1609. Returns:
  1610. The resolved delta for the state.
  1611. """
  1612. return await _resolve_delta(self.get_delta())
  1613. def _mark_dirty(self):
  1614. """Mark the substate and all parent states as dirty."""
  1615. state_name = self.get_name()
  1616. if (
  1617. self.parent_state is not None
  1618. and state_name not in self.parent_state.dirty_substates
  1619. ):
  1620. self.parent_state.dirty_substates.add(self.get_name())
  1621. self.parent_state._mark_dirty()
  1622. # have to mark computed vars dirty to allow access to newly computed
  1623. # values within the same ComputedVar function
  1624. self._mark_dirty_computed_vars()
  1625. def _update_was_touched(self):
  1626. """Update the _was_touched flag based on dirty_vars."""
  1627. if self.dirty_vars and not self._was_touched:
  1628. for var in self.dirty_vars:
  1629. if var in self.base_vars or var in self._backend_vars:
  1630. self._was_touched = True
  1631. break
  1632. if var == constants.ROUTER_DATA and self.parent_state is None:
  1633. self._was_touched = True
  1634. break
  1635. def _get_was_touched(self) -> bool:
  1636. """Check current dirty_vars and flag to determine if state instance was modified.
  1637. If any dirty vars belong to this state, mark _was_touched.
  1638. This flag determines whether this state instance should be persisted to redis.
  1639. Returns:
  1640. Whether this state instance was ever modified.
  1641. """
  1642. # Ensure the flag is up to date based on the current dirty_vars
  1643. self._update_was_touched()
  1644. return self._was_touched
  1645. def _clean(self):
  1646. """Reset the dirty vars."""
  1647. # Update touched status before cleaning dirty_vars.
  1648. self._update_was_touched()
  1649. # Recursively clean the substates.
  1650. for substate in self.dirty_substates:
  1651. if substate not in self.substates:
  1652. continue
  1653. self.substates[substate]._clean()
  1654. # Clean this state.
  1655. self.dirty_vars = set()
  1656. self.dirty_substates = set()
  1657. def get_value(self, key: str) -> Any:
  1658. """Get the value of a field (without proxying).
  1659. The returned value will NOT track dirty state updates.
  1660. Args:
  1661. key: The key of the field.
  1662. Returns:
  1663. The value of the field.
  1664. """
  1665. value = super().get_value(key)
  1666. if isinstance(value, MutableProxy):
  1667. return value.__wrapped__
  1668. return value
  1669. def dict(
  1670. self, include_computed: bool = True, initial: bool = False, **kwargs
  1671. ) -> dict[str, Any]:
  1672. """Convert the object to a dictionary.
  1673. Args:
  1674. include_computed: Whether to include computed vars.
  1675. initial: Whether to get the initial value of computed vars.
  1676. **kwargs: Kwargs to pass to the pydantic dict method.
  1677. Returns:
  1678. The object as a dictionary.
  1679. """
  1680. if include_computed:
  1681. self._mark_dirty_computed_vars()
  1682. base_vars = {
  1683. prop_name: self.get_value(prop_name) for prop_name in self.base_vars
  1684. }
  1685. if initial and include_computed:
  1686. computed_vars = {
  1687. # Include initial computed vars.
  1688. prop_name: (
  1689. cv._initial_value
  1690. if is_computed_var(cv)
  1691. and not isinstance(cv._initial_value, types.Unset)
  1692. else self.get_value(prop_name)
  1693. )
  1694. for prop_name, cv in self.computed_vars.items()
  1695. if not cv._backend
  1696. }
  1697. elif include_computed:
  1698. computed_vars = {
  1699. # Include the computed vars.
  1700. prop_name: self.get_value(prop_name)
  1701. for prop_name, cv in self.computed_vars.items()
  1702. if not cv._backend
  1703. }
  1704. else:
  1705. computed_vars = {}
  1706. variables = {**base_vars, **computed_vars}
  1707. d = {
  1708. self.get_full_name(): {k: variables[k] for k in sorted(variables)},
  1709. }
  1710. for substate_d in [
  1711. v.dict(include_computed=include_computed, initial=initial, **kwargs)
  1712. for v in self.substates.values()
  1713. ]:
  1714. d.update(substate_d)
  1715. return d
  1716. async def __aenter__(self) -> BaseState:
  1717. """Enter the async context manager protocol.
  1718. This should not be used for the State class, but exists for
  1719. type-compatibility with StateProxy.
  1720. Raises:
  1721. TypeError: always, because async contextmanager protocol is only supported for background task.
  1722. """
  1723. raise TypeError(
  1724. "Only background task should use `async with self` to modify state."
  1725. )
  1726. async def __aexit__(self, *exc_info: Any) -> None:
  1727. """Exit the async context manager protocol.
  1728. This should not be used for the State class, but exists for
  1729. type-compatibility with StateProxy.
  1730. Args:
  1731. exc_info: The exception info tuple.
  1732. """
  1733. pass
  1734. def __getstate__(self):
  1735. """Get the state for redis serialization.
  1736. This method is called by pickle to serialize the object.
  1737. It explicitly removes parent_state and substates because those are serialized separately
  1738. by the StateManagerRedis to allow for better horizontal scaling as state size increases.
  1739. Returns:
  1740. The state dict for serialization.
  1741. """
  1742. state = super().__getstate__()
  1743. state["__dict__"] = state["__dict__"].copy()
  1744. if state["__dict__"].get("parent_state") is not None:
  1745. # Do not serialize router data in substates (only the root state).
  1746. state["__dict__"].pop("router", None)
  1747. state["__dict__"].pop("router_data", None)
  1748. # Never serialize parent_state or substates.
  1749. state["__dict__"].pop("parent_state", None)
  1750. state["__dict__"].pop("substates", None)
  1751. state["__dict__"].pop("_was_touched", None)
  1752. # Remove all inherited vars.
  1753. for inherited_var_name in self.inherited_vars:
  1754. state["__dict__"].pop(inherited_var_name, None)
  1755. return state
  1756. def __setstate__(self, state: dict[str, Any]):
  1757. """Set the state from redis deserialization.
  1758. This method is called by pickle to deserialize the object.
  1759. Args:
  1760. state: The state dict for deserialization.
  1761. """
  1762. state["__dict__"]["parent_state"] = None
  1763. state["__dict__"]["substates"] = {}
  1764. super().__setstate__(state)
  1765. def _check_state_size(
  1766. self,
  1767. pickle_state_size: int,
  1768. ):
  1769. """Print a warning when the state is too large.
  1770. Args:
  1771. pickle_state_size: The size of the pickled state.
  1772. Raises:
  1773. StateTooLargeError: If the state is too large.
  1774. """
  1775. state_full_name = self.get_full_name()
  1776. if (
  1777. state_full_name not in _WARNED_ABOUT_STATE_SIZE
  1778. and pickle_state_size > TOO_LARGE_SERIALIZED_STATE
  1779. and self.substates
  1780. ):
  1781. msg = (
  1782. f"State {state_full_name} serializes to {pickle_state_size} bytes "
  1783. + "which may present performance issues. Consider reducing the size of this state."
  1784. )
  1785. if environment.REFLEX_PERF_MODE.get() == PerformanceMode.WARN:
  1786. console.warn(msg)
  1787. elif environment.REFLEX_PERF_MODE.get() == PerformanceMode.RAISE:
  1788. raise StateTooLargeError(msg)
  1789. _WARNED_ABOUT_STATE_SIZE.add(state_full_name)
  1790. @classmethod
  1791. @functools.lru_cache
  1792. def _to_schema(cls) -> str:
  1793. """Convert a state to a schema.
  1794. Returns:
  1795. The hash of the schema.
  1796. """
  1797. def _field_tuple(
  1798. field_name: str,
  1799. ) -> tuple[str, str, Any, bool | None, Any]:
  1800. model_field = cls.__fields__[field_name]
  1801. return (
  1802. field_name,
  1803. model_field.name,
  1804. _serialize_type(model_field.type_),
  1805. (
  1806. model_field.required
  1807. if isinstance(model_field.required, bool)
  1808. else None
  1809. ),
  1810. (model_field.default if is_serializable(model_field.default) else None),
  1811. )
  1812. return md5(
  1813. pickle.dumps(
  1814. sorted(_field_tuple(field_name) for field_name in cls.base_vars)
  1815. )
  1816. ).hexdigest()
  1817. def _serialize(self) -> bytes:
  1818. """Serialize the state for redis.
  1819. Returns:
  1820. The serialized state.
  1821. Raises:
  1822. StateSerializationError: If the state cannot be serialized.
  1823. """
  1824. payload = b""
  1825. error = ""
  1826. try:
  1827. payload = pickle.dumps((self._to_schema(), self))
  1828. except HANDLED_PICKLE_ERRORS as og_pickle_error:
  1829. error = (
  1830. f"Failed to serialize state {self.get_full_name()} due to unpicklable object. "
  1831. "This state will not be persisted. "
  1832. )
  1833. try:
  1834. import dill
  1835. payload = dill.dumps((self._to_schema(), self))
  1836. except ImportError:
  1837. error += (
  1838. f"Pickle error: {og_pickle_error}. "
  1839. "Consider `pip install 'dill>=0.3.8'` for more exotic serialization support."
  1840. )
  1841. except HANDLED_PICKLE_ERRORS as ex:
  1842. error += f"Dill was also unable to pickle the state: {ex}"
  1843. console.warn(error)
  1844. if environment.REFLEX_PERF_MODE.get() != PerformanceMode.OFF:
  1845. self._check_state_size(len(payload))
  1846. if not payload:
  1847. raise StateSerializationError(error)
  1848. return payload
  1849. @classmethod
  1850. def _deserialize(
  1851. cls, data: bytes | None = None, fp: BinaryIO | None = None
  1852. ) -> BaseState:
  1853. """Deserialize the state from redis/disk.
  1854. data and fp are mutually exclusive, but one must be provided.
  1855. Args:
  1856. data: The serialized state data.
  1857. fp: The file pointer to the serialized state data.
  1858. Returns:
  1859. The deserialized state.
  1860. Raises:
  1861. ValueError: If both data and fp are provided, or neither are provided.
  1862. StateSchemaMismatchError: If the state schema does not match the expected schema.
  1863. """
  1864. if data is not None and fp is None:
  1865. (substate_schema, state) = pickle.loads(data)
  1866. elif fp is not None and data is None:
  1867. (substate_schema, state) = pickle.load(fp)
  1868. else:
  1869. raise ValueError("Only one of `data` or `fp` must be provided")
  1870. if substate_schema != state._to_schema():
  1871. raise StateSchemaMismatchError()
  1872. return state
  1873. def _serialize_type(type_: Any) -> str:
  1874. """Serialize a type.
  1875. Args:
  1876. type_: The type to serialize.
  1877. Returns:
  1878. The serialized type.
  1879. """
  1880. if not inspect.isclass(type_):
  1881. return f"{type_}"
  1882. return f"{type_.__module__}.{type_.__qualname__}"
  1883. def is_serializable(value: Any) -> bool:
  1884. """Check if a value is serializable.
  1885. Args:
  1886. value: The value to check.
  1887. Returns:
  1888. Whether the value is serializable.
  1889. """
  1890. try:
  1891. return bool(pickle.dumps(value))
  1892. except Exception:
  1893. return False
  1894. T_STATE = TypeVar("T_STATE", bound=BaseState)
  1895. class State(BaseState):
  1896. """The app Base State."""
  1897. # The hydrated bool.
  1898. is_hydrated: bool = False
  1899. T = TypeVar("T", bound=BaseState)
  1900. def dynamic(func: Callable[[T], Component]):
  1901. """Create a dynamically generated components from a state class.
  1902. Args:
  1903. func: The function to generate the component.
  1904. Returns:
  1905. The dynamically generated component.
  1906. Raises:
  1907. DynamicComponentInvalidSignatureError: If the function does not have exactly one parameter or a type hint for the state class.
  1908. """
  1909. number_of_parameters = len(inspect.signature(func).parameters)
  1910. func_signature = get_type_hints(func)
  1911. if "return" in func_signature:
  1912. func_signature.pop("return")
  1913. values = list(func_signature.values())
  1914. if number_of_parameters != 1:
  1915. raise DynamicComponentInvalidSignatureError(
  1916. "The function must have exactly one parameter, which is the state class."
  1917. )
  1918. if len(values) != 1:
  1919. raise DynamicComponentInvalidSignatureError(
  1920. "You must provide a type hint for the state class in the function."
  1921. )
  1922. state_class: type[T] = values[0]
  1923. def wrapper() -> Component:
  1924. from reflex.components.base.fragment import fragment
  1925. return fragment(state_class._evaluate(lambda state: func(state)))
  1926. return wrapper
  1927. class FrontendEventExceptionState(State):
  1928. """Substate for handling frontend exceptions."""
  1929. @event
  1930. def handle_frontend_exception(self, stack: str, component_stack: str) -> None:
  1931. """Handle frontend exceptions.
  1932. If a frontend exception handler is provided, it will be called.
  1933. Otherwise, the default frontend exception handler will be called.
  1934. Args:
  1935. stack: The stack trace of the exception.
  1936. component_stack: The stack trace of the component where the exception occurred.
  1937. """
  1938. prerequisites.get_and_validate_app().app.frontend_exception_handler(
  1939. Exception(stack)
  1940. )
  1941. class UpdateVarsInternalState(State):
  1942. """Substate for handling internal state var updates."""
  1943. async def update_vars_internal(self, vars: dict[str, Any]) -> None:
  1944. """Apply updates to fully qualified state vars.
  1945. The keys in `vars` should be in the form of `{state.get_full_name()}.{var_name}`,
  1946. and each value will be set on the appropriate substate instance.
  1947. This function is primarily used to apply cookie and local storage
  1948. updates from the frontend to the appropriate substate.
  1949. Args:
  1950. vars: The fully qualified vars and values to update.
  1951. """
  1952. for var, value in vars.items():
  1953. state_name, _, var_name = var.rpartition(".")
  1954. var_state_cls = State.get_class_substate(state_name)
  1955. var_state = await self.get_state(var_state_cls)
  1956. setattr(var_state, var_name, value)
  1957. class OnLoadInternalState(State):
  1958. """Substate for handling on_load event enumeration.
  1959. This is a separate substate to avoid deserializing the entire state tree for every page navigation.
  1960. """
  1961. def on_load_internal(self) -> list[Event | EventSpec] | None:
  1962. """Queue on_load handlers for the current page.
  1963. Returns:
  1964. The list of events to queue for on load handling.
  1965. """
  1966. # Do not app._compile()! It should be already compiled by now.
  1967. load_events = prerequisites.get_and_validate_app().app.get_load_events(
  1968. self.router.page.path
  1969. )
  1970. if not load_events:
  1971. self.is_hydrated = True
  1972. return # Fast path for navigation with no on_load events defined.
  1973. self.is_hydrated = False
  1974. return [
  1975. *fix_events(
  1976. cast(list[EventSpec | EventHandler], load_events),
  1977. self.router.session.client_token,
  1978. router_data=self.router_data,
  1979. ),
  1980. State.set_is_hydrated(True), # pyright: ignore [reportAttributeAccessIssue]
  1981. ]
  1982. class ComponentState(State, mixin=True):
  1983. """Base class to allow for the creation of a state instance per component.
  1984. This allows for the bundling of UI and state logic into a single class,
  1985. where each instance has a separate instance of the state.
  1986. Subclass this class and define vars and event handlers in the traditional way.
  1987. Then define a `get_component` method that returns the UI for the component instance.
  1988. See the full [docs](https://reflex.dev/docs/substates/component-state/) for more.
  1989. Basic example:
  1990. ```python
  1991. # Subclass ComponentState and define vars and event handlers.
  1992. class Counter(rx.ComponentState):
  1993. # Define vars that change.
  1994. count: int = 0
  1995. # Define event handlers.
  1996. def increment(self):
  1997. self.count += 1
  1998. def decrement(self):
  1999. self.count -= 1
  2000. @classmethod
  2001. def get_component(cls, **props):
  2002. # Access the state vars and event handlers using `cls`.
  2003. return rx.hstack(
  2004. rx.button("Decrement", on_click=cls.decrement),
  2005. rx.text(cls.count),
  2006. rx.button("Increment", on_click=cls.increment),
  2007. **props,
  2008. )
  2009. counter = Counter.create()
  2010. ```
  2011. """
  2012. # The number of components created from this class.
  2013. _per_component_state_instance_count: ClassVar[int] = 0
  2014. def __init__(self, *args, **kwargs):
  2015. """Do not allow direct initialization of the ComponentState.
  2016. Args:
  2017. *args: The args to pass to the State init method.
  2018. **kwargs: The kwargs to pass to the State init method.
  2019. Raises:
  2020. ReflexRuntimeError: If the ComponentState is initialized directly.
  2021. """
  2022. if type(self)._mixin:
  2023. raise ReflexRuntimeError(
  2024. f"{ComponentState.__name__} {type(self).__name__} is not meant to be initialized directly. "
  2025. + "Use the `create` method to create a new instance and access the state via the `State` attribute."
  2026. )
  2027. super().__init__(*args, **kwargs)
  2028. @classmethod
  2029. def __init_subclass__(cls, mixin: bool = True, **kwargs):
  2030. """Overwrite mixin default to True.
  2031. Args:
  2032. mixin: Whether the subclass is a mixin and should not be initialized.
  2033. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  2034. """
  2035. super().__init_subclass__(mixin=mixin, **kwargs)
  2036. @classmethod
  2037. def get_component(cls, *children, **props) -> Component:
  2038. """Get the component instance.
  2039. Args:
  2040. children: The children of the component.
  2041. props: The props of the component.
  2042. Raises:
  2043. NotImplementedError: if the subclass does not override this method.
  2044. """
  2045. raise NotImplementedError(
  2046. f"{cls.__name__} must implement get_component to return the component instance."
  2047. )
  2048. @classmethod
  2049. def create(cls, *children, **props) -> Component:
  2050. """Create a new instance of the Component.
  2051. Args:
  2052. children: The children of the component.
  2053. props: The props of the component.
  2054. Returns:
  2055. A new instance of the Component with an independent copy of the State.
  2056. """
  2057. from reflex.compiler.compiler import into_component
  2058. cls._per_component_state_instance_count += 1
  2059. state_cls_name = f"{cls.__name__}_n{cls._per_component_state_instance_count}"
  2060. component_state = type(
  2061. state_cls_name,
  2062. (cls, State),
  2063. {"__module__": reflex.istate.dynamic.__name__},
  2064. mixin=False,
  2065. )
  2066. # Save a reference to the dynamic state for pickle/unpickle.
  2067. setattr(reflex.istate.dynamic, state_cls_name, component_state)
  2068. component = component_state.get_component(*children, **props)
  2069. component = into_component(component)
  2070. component.State = component_state
  2071. return component
  2072. @dataclasses.dataclass(
  2073. frozen=True,
  2074. )
  2075. class StateUpdate:
  2076. """A state update sent to the frontend."""
  2077. # The state delta.
  2078. delta: Delta = dataclasses.field(default_factory=dict)
  2079. # Events to be added to the event queue.
  2080. events: list[Event] = dataclasses.field(default_factory=list)
  2081. # Whether this is the final state update for the event.
  2082. final: bool = True
  2083. def json(self) -> str:
  2084. """Convert the state update to a JSON string.
  2085. Returns:
  2086. The state update as a JSON string.
  2087. """
  2088. return format.json_dumps(self)
  2089. def code_uses_state_contexts(javascript_code: str) -> bool:
  2090. """Check if the rendered Javascript uses state contexts.
  2091. Args:
  2092. javascript_code: The Javascript code to check.
  2093. Returns:
  2094. True if the code attempts to access a member of StateContexts.
  2095. """
  2096. return bool("useContext(StateContexts" in javascript_code)
  2097. def reload_state_module(
  2098. module: str,
  2099. state: type[BaseState] = State,
  2100. ) -> None:
  2101. """Reset rx.State subclasses to avoid conflict when reloading.
  2102. Args:
  2103. module: The module to reload.
  2104. state: Recursive argument for the state class to reload.
  2105. """
  2106. # Clean out all potentially dirty states of reloaded modules.
  2107. for pd_state in tuple(state._potentially_dirty_states):
  2108. with contextlib.suppress(ValueError):
  2109. if (
  2110. state.get_root_state().get_class_substate(pd_state).__module__ == module
  2111. and module is not None
  2112. ):
  2113. state._potentially_dirty_states.remove(pd_state)
  2114. for subclass in tuple(state.class_subclasses):
  2115. reload_state_module(module=module, state=subclass)
  2116. if subclass.__module__ == module and module is not None:
  2117. all_base_state_classes.pop(subclass.get_full_name(), None)
  2118. state.class_subclasses.remove(subclass)
  2119. state._always_dirty_substates.discard(subclass.get_name())
  2120. state._var_dependencies = {}
  2121. state._init_var_dependency_dicts()
  2122. state.get_class_substate.cache_clear()
  2123. from reflex.istate.manager import LockExpiredError as LockExpiredError # noqa: E402
  2124. from reflex.istate.manager import StateManager as StateManager # noqa: E402
  2125. from reflex.istate.manager import StateManagerDisk as StateManagerDisk # noqa: E402
  2126. from reflex.istate.manager import StateManagerMemory as StateManagerMemory # noqa: E402
  2127. from reflex.istate.manager import StateManagerRedis as StateManagerRedis # noqa: E402
  2128. from reflex.istate.manager import get_state_manager as get_state_manager # noqa: E402
  2129. from reflex.istate.manager import ( # noqa: E402
  2130. reset_disk_state_manager as reset_disk_state_manager,
  2131. )