state.py 88 KB

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