base.py 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  1. """Collection of base classes."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import datetime
  6. import functools
  7. import inspect
  8. import json
  9. import random
  10. import re
  11. import string
  12. import uuid
  13. import warnings
  14. from types import CodeType, FunctionType
  15. from typing import (
  16. TYPE_CHECKING,
  17. Any,
  18. Callable,
  19. ClassVar,
  20. Coroutine,
  21. Dict,
  22. FrozenSet,
  23. Generic,
  24. Iterable,
  25. List,
  26. Literal,
  27. Mapping,
  28. NoReturn,
  29. Optional,
  30. Sequence,
  31. Set,
  32. Tuple,
  33. Type,
  34. TypeVar,
  35. Union,
  36. cast,
  37. get_args,
  38. overload,
  39. )
  40. from sqlalchemy.orm import DeclarativeBase
  41. from typing_extensions import ParamSpec, TypeGuard, deprecated, get_type_hints, override
  42. from reflex import constants
  43. from reflex.base import Base
  44. from reflex.constants.compiler import Hooks
  45. from reflex.utils import console, exceptions, imports, serializers, types
  46. from reflex.utils.exceptions import (
  47. ComputedVarSignatureError,
  48. UntypedComputedVarError,
  49. VarAttributeError,
  50. VarDependencyError,
  51. VarTypeError,
  52. )
  53. from reflex.utils.format import format_state_name
  54. from reflex.utils.imports import (
  55. ImmutableParsedImportDict,
  56. ImportDict,
  57. ImportVar,
  58. ParsedImportDict,
  59. parse_imports,
  60. )
  61. from reflex.utils.types import (
  62. GenericType,
  63. Self,
  64. _isinstance,
  65. get_origin,
  66. has_args,
  67. safe_issubclass,
  68. unionize,
  69. )
  70. if TYPE_CHECKING:
  71. from reflex.state import BaseState
  72. from .number import BooleanVar, LiteralBooleanVar, LiteralNumberVar, NumberVar
  73. from .object import LiteralObjectVar, ObjectVar
  74. from .sequence import ArrayVar, LiteralArrayVar, LiteralStringVar, StringVar
  75. VAR_TYPE = TypeVar("VAR_TYPE", covariant=True)
  76. OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE")
  77. STRING_T = TypeVar("STRING_T", bound=str)
  78. SEQUENCE_TYPE = TypeVar("SEQUENCE_TYPE", bound=Sequence)
  79. warnings.filterwarnings("ignore", message="fields may not start with an underscore")
  80. @dataclasses.dataclass(
  81. eq=False,
  82. frozen=True,
  83. )
  84. class VarSubclassEntry:
  85. """Entry for a Var subclass."""
  86. var_subclass: Type[Var]
  87. to_var_subclass: Type[ToOperation]
  88. python_types: Tuple[GenericType, ...]
  89. _var_subclasses: List[VarSubclassEntry] = []
  90. _var_literal_subclasses: List[Tuple[Type[LiteralVar], VarSubclassEntry]] = []
  91. @dataclasses.dataclass(
  92. eq=True,
  93. frozen=True,
  94. )
  95. class VarData:
  96. """Metadata associated with a x."""
  97. # The name of the enclosing state.
  98. state: str = dataclasses.field(default="")
  99. # The name of the field in the state.
  100. field_name: str = dataclasses.field(default="")
  101. # Imports needed to render this var
  102. imports: ImmutableParsedImportDict = dataclasses.field(default_factory=tuple)
  103. # Hooks that need to be present in the component to render this var
  104. hooks: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
  105. # Dependencies of the var
  106. deps: Tuple[Var, ...] = dataclasses.field(default_factory=tuple)
  107. # Position of the hook in the component
  108. position: Hooks.HookPosition | None = None
  109. def __init__(
  110. self,
  111. state: str = "",
  112. field_name: str = "",
  113. imports: ImportDict | ParsedImportDict | None = None,
  114. hooks: Mapping[str, VarData | None] | Sequence[str] | str | None = None,
  115. deps: list[Var] | None = None,
  116. position: Hooks.HookPosition | None = None,
  117. ):
  118. """Initialize the var data.
  119. Args:
  120. state: The name of the enclosing state.
  121. field_name: The name of the field in the state.
  122. imports: Imports needed to render this var.
  123. hooks: Hooks that need to be present in the component to render this var.
  124. deps: Dependencies of the var for useCallback.
  125. position: Position of the hook in the component.
  126. """
  127. if isinstance(hooks, str):
  128. hooks = [hooks]
  129. if not isinstance(hooks, dict):
  130. hooks = {hook: None for hook in (hooks or [])}
  131. immutable_imports: ImmutableParsedImportDict = tuple(
  132. (k, tuple(v)) for k, v in parse_imports(imports or {}).items()
  133. )
  134. object.__setattr__(self, "state", state)
  135. object.__setattr__(self, "field_name", field_name)
  136. object.__setattr__(self, "imports", immutable_imports)
  137. object.__setattr__(self, "hooks", tuple(hooks or {}))
  138. object.__setattr__(self, "deps", tuple(deps or []))
  139. object.__setattr__(self, "position", position or None)
  140. if hooks and any(hooks.values()):
  141. merged_var_data = VarData.merge(self, *hooks.values())
  142. if merged_var_data is not None:
  143. object.__setattr__(self, "state", merged_var_data.state)
  144. object.__setattr__(self, "field_name", merged_var_data.field_name)
  145. object.__setattr__(self, "imports", merged_var_data.imports)
  146. object.__setattr__(self, "hooks", merged_var_data.hooks)
  147. object.__setattr__(self, "deps", merged_var_data.deps)
  148. object.__setattr__(self, "position", merged_var_data.position)
  149. def old_school_imports(self) -> ImportDict:
  150. """Return the imports as a mutable dict.
  151. Returns:
  152. The imports as a mutable dict.
  153. """
  154. return {k: list(v) for k, v in self.imports}
  155. def merge(*all: VarData | None) -> VarData | None:
  156. """Merge multiple var data objects.
  157. Args:
  158. *all: The var data objects to merge.
  159. Raises:
  160. ReflexError: If trying to merge VarData with different positions.
  161. Returns:
  162. The merged var data object.
  163. # noqa: DAR102 *all
  164. """
  165. all_var_datas = list(filter(None, all))
  166. if not all_var_datas:
  167. return None
  168. if len(all_var_datas) == 1:
  169. return all_var_datas[0]
  170. # Get the first non-empty field name or default to empty string.
  171. field_name = next(
  172. (var_data.field_name for var_data in all_var_datas if var_data.field_name),
  173. "",
  174. )
  175. # Get the first non-empty state or default to empty string.
  176. state = next(
  177. (var_data.state for var_data in all_var_datas if var_data.state), ""
  178. )
  179. hooks: dict[str, VarData | None] = {
  180. hook: None for var_data in all_var_datas for hook in var_data.hooks
  181. }
  182. _imports = imports.merge_imports(
  183. *(var_data.imports for var_data in all_var_datas)
  184. )
  185. deps = [dep for var_data in all_var_datas for dep in var_data.deps]
  186. positions = list(
  187. {
  188. var_data.position
  189. for var_data in all_var_datas
  190. if var_data.position is not None
  191. }
  192. )
  193. if positions:
  194. if len(positions) > 1:
  195. raise exceptions.ReflexError(
  196. f"Cannot merge var data with different positions: {positions}"
  197. )
  198. position = positions[0]
  199. else:
  200. position = None
  201. if state or _imports or hooks or field_name or deps or position:
  202. return VarData(
  203. state=state,
  204. field_name=field_name,
  205. imports=_imports,
  206. hooks=hooks,
  207. deps=deps,
  208. position=position,
  209. )
  210. return None
  211. def __bool__(self) -> bool:
  212. """Check if the var data is non-empty.
  213. Returns:
  214. True if any field is set to a non-default value.
  215. """
  216. return bool(
  217. self.state
  218. or self.imports
  219. or self.hooks
  220. or self.field_name
  221. or self.deps
  222. or self.position
  223. )
  224. @classmethod
  225. def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarData:
  226. """Set the state of the var.
  227. Args:
  228. state: The state to set or the full name of the state.
  229. field_name: The name of the field in the state. Optional.
  230. Returns:
  231. The var with the set state.
  232. """
  233. from reflex.utils import format
  234. state_name = state if isinstance(state, str) else state.get_full_name()
  235. return VarData(
  236. state=state_name,
  237. field_name=field_name,
  238. hooks={
  239. "const {0} = useContext(StateContexts.{0})".format(
  240. format.format_state_name(state_name)
  241. ): None
  242. },
  243. imports={
  244. f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  245. "react": [ImportVar(tag="useContext")],
  246. },
  247. )
  248. def _decode_var_immutable(value: str) -> tuple[VarData | None, str]:
  249. """Decode the state name from a formatted var.
  250. Args:
  251. value: The value to extract the state name from.
  252. Returns:
  253. The extracted state name and the value without the state name.
  254. """
  255. var_datas = []
  256. if isinstance(value, str):
  257. # fast path if there is no encoded VarData
  258. if constants.REFLEX_VAR_OPENING_TAG not in value:
  259. return None, value
  260. offset = 0
  261. # Find all tags.
  262. while m := _decode_var_pattern.search(value):
  263. start, end = m.span()
  264. value = value[:start] + value[end:]
  265. serialized_data = m.group(1)
  266. if serialized_data.isnumeric() or (
  267. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  268. ):
  269. # This is a global immutable var.
  270. var = _global_vars[int(serialized_data)]
  271. var_data = var._get_all_var_data()
  272. if var_data is not None:
  273. var_datas.append(var_data)
  274. offset += end - start
  275. return VarData.merge(*var_datas) if var_datas else None, value
  276. def can_use_in_object_var(cls: GenericType) -> bool:
  277. """Check if the class can be used in an ObjectVar.
  278. Args:
  279. cls: The class to check.
  280. Returns:
  281. Whether the class can be used in an ObjectVar.
  282. """
  283. if types.is_union(cls):
  284. return all(can_use_in_object_var(t) for t in types.get_args(cls))
  285. return (
  286. inspect.isclass(cls)
  287. and not issubclass(cls, Var)
  288. and serializers.can_serialize(cls, dict)
  289. )
  290. @dataclasses.dataclass(
  291. eq=False,
  292. frozen=True,
  293. )
  294. class Var(Generic[VAR_TYPE]):
  295. """Base class for immutable vars."""
  296. # The name of the var.
  297. _js_expr: str = dataclasses.field()
  298. # The type of the var.
  299. _var_type: types.GenericType = dataclasses.field(default=Any)
  300. # Extra metadata associated with the Var
  301. _var_data: Optional[VarData] = dataclasses.field(default=None)
  302. def __str__(self) -> str:
  303. """String representation of the var. Guaranteed to be a valid Javascript expression.
  304. Returns:
  305. The name of the var.
  306. """
  307. return self._js_expr
  308. @property
  309. def _var_is_local(self) -> bool:
  310. """Whether this is a local javascript variable.
  311. Returns:
  312. False
  313. """
  314. return False
  315. @property
  316. @deprecated("Use `_js_expr` instead.")
  317. def _var_name(self) -> str:
  318. """The name of the var.
  319. Returns:
  320. The name of the var.
  321. """
  322. return self._js_expr
  323. @property
  324. def _var_field_name(self) -> str:
  325. """The name of the field.
  326. Returns:
  327. The name of the field.
  328. """
  329. var_data = self._get_all_var_data()
  330. field_name = var_data.field_name if var_data else None
  331. return field_name or self._js_expr
  332. @property
  333. @deprecated("Use `_js_expr` instead.")
  334. def _var_name_unwrapped(self) -> str:
  335. """The name of the var without extra curly braces.
  336. Returns:
  337. The name of the var.
  338. """
  339. return self._js_expr
  340. @property
  341. def _var_is_string(self) -> bool:
  342. """Whether the var is a string literal.
  343. Returns:
  344. False
  345. """
  346. return False
  347. def __init_subclass__(
  348. cls,
  349. python_types: Tuple[GenericType, ...] | GenericType = types.Unset(),
  350. default_type: GenericType = types.Unset(),
  351. **kwargs,
  352. ):
  353. """Initialize the subclass.
  354. Args:
  355. python_types: The python types that the var represents.
  356. default_type: The default type of the var. Defaults to the first python type.
  357. **kwargs: Additional keyword arguments.
  358. """
  359. super().__init_subclass__(**kwargs)
  360. if python_types or default_type:
  361. python_types = (
  362. (python_types if isinstance(python_types, tuple) else (python_types,))
  363. if python_types
  364. else ()
  365. )
  366. default_type = default_type or (python_types[0] if python_types else Any)
  367. @dataclasses.dataclass(
  368. eq=False,
  369. frozen=True,
  370. slots=True,
  371. )
  372. class ToVarOperation(ToOperation, cls):
  373. """Base class of converting a var to another var type."""
  374. _original: Var = dataclasses.field(
  375. default=Var(_js_expr="null", _var_type=None),
  376. )
  377. _default_var_type: ClassVar[GenericType] = default_type
  378. new_to_var_operation_name = f"To{cls.__name__.removesuffix('Var')}Operation"
  379. ToVarOperation.__qualname__ = (
  380. ToVarOperation.__qualname__.removesuffix(ToVarOperation.__name__)
  381. + new_to_var_operation_name
  382. )
  383. ToVarOperation.__name__ = new_to_var_operation_name
  384. _var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types))
  385. def __post_init__(self):
  386. """Post-initialize the var."""
  387. # Decode any inline Var markup and apply it to the instance
  388. _var_data, _js_expr = _decode_var_immutable(self._js_expr)
  389. if _var_data or _js_expr != self._js_expr:
  390. self.__init__(
  391. _js_expr=_js_expr,
  392. _var_type=self._var_type,
  393. _var_data=VarData.merge(self._var_data, _var_data),
  394. )
  395. def __hash__(self) -> int:
  396. """Define a hash function for the var.
  397. Returns:
  398. The hash of the var.
  399. """
  400. return hash((self._js_expr, self._var_type, self._var_data))
  401. def _get_all_var_data(self) -> VarData | None:
  402. """Get all VarData associated with the Var.
  403. Returns:
  404. The VarData of the components and all of its children.
  405. """
  406. return self._var_data
  407. def equals(self, other: Var) -> bool:
  408. """Check if two vars are equal.
  409. Args:
  410. other: The other var to compare.
  411. Returns:
  412. Whether the vars are equal.
  413. """
  414. return (
  415. self._js_expr == other._js_expr
  416. and self._var_type == other._var_type
  417. and self._get_all_var_data() == other._get_all_var_data()
  418. )
  419. @overload
  420. def _replace(
  421. self,
  422. _var_type: Type[OTHER_VAR_TYPE],
  423. merge_var_data: VarData | None = None,
  424. **kwargs: Any,
  425. ) -> Var[OTHER_VAR_TYPE]: ...
  426. @overload
  427. def _replace(
  428. self,
  429. _var_type: GenericType | None = None,
  430. merge_var_data: VarData | None = None,
  431. **kwargs: Any,
  432. ) -> Self: ...
  433. def _replace(
  434. self,
  435. _var_type: GenericType | None = None,
  436. merge_var_data: VarData | None = None,
  437. **kwargs: Any,
  438. ) -> Self | Var:
  439. """Make a copy of this Var with updated fields.
  440. Args:
  441. _var_type: The new type of the Var.
  442. merge_var_data: VarData to merge into the existing VarData.
  443. **kwargs: Var fields to update.
  444. Returns:
  445. A new Var with the updated fields overwriting the corresponding fields in this Var.
  446. Raises:
  447. TypeError: If _var_is_local, _var_is_string, or _var_full_name_needs_state_prefix is not None.
  448. """
  449. if kwargs.get("_var_is_local", False) is not False:
  450. raise TypeError("The _var_is_local argument is not supported for Var.")
  451. if kwargs.get("_var_is_string", False) is not False:
  452. raise TypeError("The _var_is_string argument is not supported for Var.")
  453. if kwargs.get("_var_full_name_needs_state_prefix", False) is not False:
  454. raise TypeError(
  455. "The _var_full_name_needs_state_prefix argument is not supported for Var."
  456. )
  457. value_with_replaced = dataclasses.replace(
  458. self,
  459. _var_type=_var_type or self._var_type,
  460. _var_data=VarData.merge(
  461. kwargs.get("_var_data", self._var_data), merge_var_data
  462. ),
  463. **kwargs,
  464. )
  465. if (js_expr := kwargs.get("_js_expr")) is not None:
  466. object.__setattr__(value_with_replaced, "_js_expr", js_expr)
  467. return value_with_replaced
  468. @overload
  469. @classmethod
  470. def create( # pyright: ignore[reportOverlappingOverload]
  471. cls,
  472. value: NoReturn,
  473. _var_data: VarData | None = None,
  474. ) -> Var[Any]: ...
  475. @overload
  476. @classmethod
  477. def create( # pyright: ignore[reportOverlappingOverload]
  478. cls,
  479. value: bool,
  480. _var_data: VarData | None = None,
  481. ) -> LiteralBooleanVar: ...
  482. @overload
  483. @classmethod
  484. def create(
  485. cls,
  486. value: int,
  487. _var_data: VarData | None = None,
  488. ) -> LiteralNumberVar[int]: ...
  489. @overload
  490. @classmethod
  491. def create(
  492. cls,
  493. value: float,
  494. _var_data: VarData | None = None,
  495. ) -> LiteralNumberVar[float]: ...
  496. @overload
  497. @classmethod
  498. def create( # pyright: ignore [reportOverlappingOverload]
  499. cls,
  500. value: str,
  501. _var_data: VarData | None = None,
  502. ) -> LiteralStringVar: ...
  503. @overload
  504. @classmethod
  505. def create( # pyright: ignore [reportOverlappingOverload]
  506. cls,
  507. value: STRING_T,
  508. _var_data: VarData | None = None,
  509. ) -> StringVar[STRING_T]: ...
  510. @overload
  511. @classmethod
  512. def create( # pyright: ignore[reportOverlappingOverload]
  513. cls,
  514. value: None,
  515. _var_data: VarData | None = None,
  516. ) -> LiteralNoneVar: ...
  517. @overload
  518. @classmethod
  519. def create(
  520. cls,
  521. value: MAPPING_TYPE,
  522. _var_data: VarData | None = None,
  523. ) -> LiteralObjectVar[MAPPING_TYPE]: ...
  524. @overload
  525. @classmethod
  526. def create(
  527. cls,
  528. value: SEQUENCE_TYPE,
  529. _var_data: VarData | None = None,
  530. ) -> LiteralArrayVar[SEQUENCE_TYPE]: ...
  531. @overload
  532. @classmethod
  533. def create(
  534. cls,
  535. value: OTHER_VAR_TYPE,
  536. _var_data: VarData | None = None,
  537. ) -> Var[OTHER_VAR_TYPE]: ...
  538. @classmethod
  539. def create(
  540. cls,
  541. value: OTHER_VAR_TYPE,
  542. _var_data: VarData | None = None,
  543. ) -> Var[OTHER_VAR_TYPE]:
  544. """Create a var from a value.
  545. Args:
  546. value: The value to create the var from.
  547. _var_data: Additional hooks and imports associated with the Var.
  548. Returns:
  549. The var.
  550. """
  551. # If the value is already a var, do nothing.
  552. if isinstance(value, Var):
  553. return value
  554. return LiteralVar.create(value, _var_data=_var_data)
  555. @classmethod
  556. @deprecated("Use `.create()` instead.")
  557. def create_safe(
  558. cls,
  559. *args: Any,
  560. **kwargs: Any,
  561. ) -> Var:
  562. """Create a var from a value.
  563. Args:
  564. *args: The arguments to create the var from.
  565. **kwargs: The keyword arguments to create the var from.
  566. Returns:
  567. The var.
  568. """
  569. return cls.create(*args, **kwargs)
  570. def __format__(self, format_spec: str) -> str:
  571. """Format the var into a Javascript equivalent to an f-string.
  572. Args:
  573. format_spec: The format specifier (Ignored for now).
  574. Returns:
  575. The formatted var.
  576. """
  577. hashed_var = hash(self)
  578. _global_vars[hashed_var] = self
  579. # Encode the _var_data into the formatted output for tracking purposes.
  580. return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}"
  581. @overload
  582. def to(self, output: Type[str]) -> StringVar: ...
  583. @overload
  584. def to(self, output: Type[bool]) -> BooleanVar: ...
  585. @overload
  586. def to(self, output: type[int] | type[float]) -> NumberVar: ...
  587. @overload
  588. def to(
  589. self,
  590. output: type[list] | type[tuple] | type[set],
  591. ) -> ArrayVar: ...
  592. @overload
  593. def to(
  594. self,
  595. output: type[MAPPING_TYPE],
  596. ) -> ObjectVar[MAPPING_TYPE]: ...
  597. @overload
  598. def to(
  599. self, output: Type[ObjectVar], var_type: Type[VAR_INSIDE]
  600. ) -> ObjectVar[VAR_INSIDE]: ...
  601. @overload
  602. def to(
  603. self, output: Type[ObjectVar], var_type: None = None
  604. ) -> ObjectVar[VAR_TYPE]: ...
  605. @overload
  606. def to(self, output: VAR_SUBCLASS, var_type: None = None) -> VAR_SUBCLASS: ...
  607. @overload
  608. def to(
  609. self,
  610. output: Type[OUTPUT] | types.GenericType,
  611. var_type: types.GenericType | None = None,
  612. ) -> OUTPUT: ...
  613. def to(
  614. self,
  615. output: Type[OUTPUT] | types.GenericType,
  616. var_type: types.GenericType | None = None,
  617. ) -> Var:
  618. """Convert the var to a different type.
  619. Args:
  620. output: The output type.
  621. var_type: The type of the var.
  622. Returns:
  623. The converted var.
  624. """
  625. from .object import ObjectVar
  626. fixed_output_type = get_origin(output) or output
  627. # If the first argument is a python type, we map it to the corresponding Var type.
  628. for var_subclass in _var_subclasses[::-1]:
  629. if fixed_output_type in var_subclass.python_types or safe_issubclass(
  630. fixed_output_type, var_subclass.python_types
  631. ):
  632. return self.to(var_subclass.var_subclass, output)
  633. if fixed_output_type is None:
  634. return get_to_operation(NoneVar).create(self) # pyright: ignore [reportReturnType]
  635. # Handle fixed_output_type being Base or a dataclass.
  636. if can_use_in_object_var(output):
  637. return self.to(ObjectVar, output)
  638. if inspect.isclass(output):
  639. for var_subclass in _var_subclasses[::-1]:
  640. if issubclass(output, var_subclass.var_subclass):
  641. current_var_type = self._var_type
  642. if current_var_type is Any:
  643. new_var_type = var_type
  644. else:
  645. new_var_type = var_type or current_var_type
  646. to_operation_return = var_subclass.to_var_subclass.create(
  647. value=self, _var_type=new_var_type
  648. )
  649. return to_operation_return # pyright: ignore [reportReturnType]
  650. # If we can't determine the first argument, we just replace the _var_type.
  651. if not issubclass(output, Var) or var_type is None:
  652. return dataclasses.replace(
  653. self,
  654. _var_type=output,
  655. )
  656. # We couldn't determine the output type to be any other Var type, so we replace the _var_type.
  657. if var_type is not None:
  658. return dataclasses.replace(
  659. self,
  660. _var_type=var_type,
  661. )
  662. return self
  663. @overload
  664. def guess_type(self: Var[NoReturn]) -> Var[Any]: ... # pyright: ignore [reportOverlappingOverload]
  665. @overload
  666. def guess_type(self: Var[str]) -> StringVar: ...
  667. @overload
  668. def guess_type(self: Var[bool]) -> BooleanVar: ...
  669. @overload
  670. def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ...
  671. @overload
  672. def guess_type(self: Var[BASE_TYPE]) -> ObjectVar[BASE_TYPE]: ...
  673. @overload
  674. def guess_type(self) -> Self: ...
  675. def guess_type(self) -> Var:
  676. """Guesses the type of the variable based on its `_var_type` attribute.
  677. Returns:
  678. Var: The guessed type of the variable.
  679. Raises:
  680. TypeError: If the type is not supported for guessing.
  681. """
  682. from .number import NumberVar
  683. from .object import ObjectVar
  684. var_type = self._var_type
  685. if var_type is None:
  686. return self.to(None)
  687. if types.is_optional(var_type):
  688. var_type = types.get_args(var_type)[0]
  689. if var_type is Any:
  690. return self
  691. fixed_type = get_origin(var_type) or var_type
  692. if fixed_type in types.UnionTypes:
  693. inner_types = get_args(var_type)
  694. if all(
  695. inspect.isclass(t) and issubclass(t, (int, float)) for t in inner_types
  696. ):
  697. return self.to(NumberVar, self._var_type)
  698. if can_use_in_object_var(var_type):
  699. return self.to(ObjectVar, self._var_type)
  700. return self
  701. if fixed_type is Literal:
  702. args = get_args(var_type)
  703. fixed_type = unionize(*(type(arg) for arg in args))
  704. if not inspect.isclass(fixed_type):
  705. raise TypeError(f"Unsupported type {var_type} for guess_type.")
  706. if fixed_type is None:
  707. return self.to(None)
  708. for var_subclass in _var_subclasses[::-1]:
  709. if issubclass(fixed_type, var_subclass.python_types):
  710. return self.to(var_subclass.var_subclass, self._var_type)
  711. if can_use_in_object_var(fixed_type):
  712. return self.to(ObjectVar, self._var_type)
  713. return self
  714. def _get_default_value(self) -> Any:
  715. """Get the default value of the var.
  716. Returns:
  717. The default value of the var.
  718. Raises:
  719. ImportError: If the var is a dataframe and pandas is not installed.
  720. """
  721. if types.is_optional(self._var_type):
  722. return None
  723. type_ = (
  724. get_origin(self._var_type)
  725. if types.is_generic_alias(self._var_type)
  726. else self._var_type
  727. )
  728. if type_ is Literal:
  729. args = get_args(self._var_type)
  730. return args[0] if args else None
  731. if issubclass(type_, str):
  732. return ""
  733. if issubclass(type_, types.get_args(Union[int, float])):
  734. return 0
  735. if issubclass(type_, bool):
  736. return False
  737. if issubclass(type_, list):
  738. return []
  739. if issubclass(type_, Mapping):
  740. return {}
  741. if issubclass(type_, tuple):
  742. return ()
  743. if types.is_dataframe(type_):
  744. try:
  745. import pandas as pd
  746. return pd.DataFrame()
  747. except ImportError as e:
  748. raise ImportError(
  749. "Please install pandas to use dataframes in your app."
  750. ) from e
  751. return set() if issubclass(type_, set) else None
  752. def _get_setter_name(self, include_state: bool = True) -> str:
  753. """Get the name of the var's generated setter function.
  754. Args:
  755. include_state: Whether to include the state name in the setter name.
  756. Returns:
  757. The name of the setter function.
  758. """
  759. setter = constants.SETTER_PREFIX + self._var_field_name
  760. var_data = self._get_all_var_data()
  761. if var_data is None:
  762. return setter
  763. if not include_state or var_data.state == "":
  764. return setter
  765. return ".".join((var_data.state, setter))
  766. def _get_setter(self) -> Callable[[BaseState, Any], None]:
  767. """Get the var's setter function.
  768. Returns:
  769. A function that that creates a setter for the var.
  770. """
  771. actual_name = self._var_field_name
  772. def setter(state: Any, value: Any):
  773. """Get the setter for the var.
  774. Args:
  775. state: The state within which we add the setter function.
  776. value: The value to set.
  777. """
  778. if self._var_type in [int, float]:
  779. try:
  780. value = self._var_type(value)
  781. setattr(state, actual_name, value)
  782. except ValueError:
  783. console.debug(
  784. f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
  785. )
  786. else:
  787. setattr(state, actual_name, value)
  788. setter.__annotations__["value"] = self._var_type
  789. setter.__qualname__ = self._get_setter_name()
  790. return setter
  791. def _var_set_state(self, state: type[BaseState] | str) -> Self:
  792. """Set the state of the var.
  793. Args:
  794. state: The state to set.
  795. Returns:
  796. The var with the state set.
  797. """
  798. formatted_state_name = (
  799. state
  800. if isinstance(state, str)
  801. else format_state_name(state.get_full_name())
  802. )
  803. return StateOperation.create( # pyright: ignore [reportReturnType]
  804. formatted_state_name,
  805. self,
  806. _var_data=VarData.merge(
  807. VarData.from_state(state, self._js_expr), self._var_data
  808. ),
  809. ).guess_type()
  810. def __eq__(self, other: Var | Any) -> BooleanVar:
  811. """Check if the current variable is equal to the given variable.
  812. Args:
  813. other (Var | Any): The variable to compare with.
  814. Returns:
  815. BooleanVar: A BooleanVar object representing the result of the equality check.
  816. """
  817. from .number import equal_operation
  818. return equal_operation(self, other)
  819. def __ne__(self, other: Var | Any) -> BooleanVar:
  820. """Check if the current object is not equal to the given object.
  821. Parameters:
  822. other (Var | Any): The object to compare with.
  823. Returns:
  824. BooleanVar: A BooleanVar object representing the result of the comparison.
  825. """
  826. from .number import equal_operation
  827. return ~equal_operation(self, other)
  828. def bool(self) -> BooleanVar:
  829. """Convert the var to a boolean.
  830. Returns:
  831. The boolean var.
  832. """
  833. from .number import boolify
  834. return boolify(self)
  835. def __and__(self, other: Var | Any) -> Var:
  836. """Perform a logical AND operation on the current instance and another variable.
  837. Args:
  838. other: The variable to perform the logical AND operation with.
  839. Returns:
  840. A `BooleanVar` object representing the result of the logical AND operation.
  841. """
  842. return and_operation(self, other)
  843. def __rand__(self, other: Var | Any) -> Var:
  844. """Perform a logical AND operation on the current instance and another variable.
  845. Args:
  846. other: The variable to perform the logical AND operation with.
  847. Returns:
  848. A `BooleanVar` object representing the result of the logical AND operation.
  849. """
  850. return and_operation(other, self)
  851. def __or__(self, other: Var | Any) -> Var:
  852. """Perform a logical OR operation on the current instance and another variable.
  853. Args:
  854. other: The variable to perform the logical OR operation with.
  855. Returns:
  856. A `BooleanVar` object representing the result of the logical OR operation.
  857. """
  858. return or_operation(self, other)
  859. def __ror__(self, other: Var | Any) -> Var:
  860. """Perform a logical OR operation on the current instance and another variable.
  861. Args:
  862. other: The variable to perform the logical OR operation with.
  863. Returns:
  864. A `BooleanVar` object representing the result of the logical OR operation.
  865. """
  866. return or_operation(other, self)
  867. def __invert__(self) -> BooleanVar:
  868. """Perform a logical NOT operation on the current instance.
  869. Returns:
  870. A `BooleanVar` object representing the result of the logical NOT operation.
  871. """
  872. return ~self.bool()
  873. def to_string(self, use_json: bool = True) -> StringVar:
  874. """Convert the var to a string.
  875. Args:
  876. use_json: Whether to use JSON stringify. If False, uses Object.prototype.toString.
  877. Returns:
  878. The string var.
  879. """
  880. from .function import JSON_STRINGIFY, PROTOTYPE_TO_STRING
  881. from .sequence import StringVar
  882. return (
  883. JSON_STRINGIFY.call(self).to(StringVar)
  884. if use_json
  885. else PROTOTYPE_TO_STRING.call(self).to(StringVar)
  886. )
  887. def _as_ref(self) -> Var:
  888. """Get a reference to the var.
  889. Returns:
  890. The reference to the var.
  891. """
  892. from .object import ObjectVar
  893. refs = Var(
  894. _js_expr="refs",
  895. _var_data=VarData(
  896. imports={
  897. f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
  898. }
  899. ),
  900. ).to(ObjectVar, Mapping[str, str])
  901. return refs[LiteralVar.create(str(self))]
  902. @deprecated("Use `.js_type()` instead.")
  903. def _type(self) -> StringVar:
  904. """Returns the type of the object.
  905. This method uses the `typeof` function from the `FunctionStringVar` class
  906. to determine the type of the object.
  907. Returns:
  908. StringVar: A string variable representing the type of the object.
  909. """
  910. return self.js_type()
  911. def js_type(self) -> StringVar:
  912. """Returns the javascript type of the object.
  913. This method uses the `typeof` function from the `FunctionStringVar` class
  914. to determine the type of the object.
  915. Returns:
  916. StringVar: A string variable representing the type of the object.
  917. """
  918. from .function import FunctionStringVar
  919. from .sequence import StringVar
  920. type_of = FunctionStringVar("typeof")
  921. return type_of.call(self).to(StringVar)
  922. def _without_data(self):
  923. """Create a copy of the var without the data.
  924. Returns:
  925. The var without the data.
  926. """
  927. return dataclasses.replace(self, _var_data=None)
  928. def __get__(self, instance: Any, owner: Any):
  929. """Get the var.
  930. Args:
  931. instance: The instance to get the var from.
  932. owner: The owner of the var.
  933. Returns:
  934. The var.
  935. """
  936. return self
  937. def _decode(self) -> Any:
  938. """Decode Var as a python value.
  939. Note that Var with state set cannot be decoded python-side and will be
  940. returned as full_name.
  941. Returns:
  942. The decoded value or the Var name.
  943. """
  944. if isinstance(self, LiteralVar):
  945. return self._var_value
  946. try:
  947. return json.loads(str(self))
  948. except ValueError:
  949. return str(self)
  950. @property
  951. def _var_state(self) -> str:
  952. """Compat method for getting the state.
  953. Returns:
  954. The state name associated with the var.
  955. """
  956. var_data = self._get_all_var_data()
  957. return var_data.state if var_data else ""
  958. @overload
  959. @classmethod
  960. def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
  961. @overload
  962. @classmethod
  963. def range(
  964. cls,
  965. start: int | NumberVar,
  966. end: int | NumberVar,
  967. step: int | NumberVar = 1,
  968. /,
  969. ) -> ArrayVar[List[int]]: ...
  970. @classmethod
  971. def range(
  972. cls,
  973. first_endpoint: int | NumberVar,
  974. second_endpoint: int | NumberVar | None = None,
  975. step: int | NumberVar | None = None,
  976. ) -> ArrayVar[List[int]]:
  977. """Create a range of numbers.
  978. Args:
  979. first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
  980. second_endpoint: The end of the range.
  981. step: The step of the range.
  982. Returns:
  983. The range of numbers.
  984. """
  985. from .sequence import ArrayVar
  986. return ArrayVar.range(first_endpoint, second_endpoint, step)
  987. if not TYPE_CHECKING:
  988. def __getattr__(self, name: str):
  989. """Get an attribute of the var.
  990. Args:
  991. name: The name of the attribute.
  992. Raises:
  993. VarAttributeError: If the attribute does not exist.
  994. UntypedVarError: If the var type is Any.
  995. TypeError: If the var type is Any.
  996. # noqa: DAR101 self
  997. """
  998. if name.startswith("_"):
  999. raise VarAttributeError(f"Attribute {name} not found.")
  1000. if name == "contains":
  1001. raise TypeError(
  1002. f"Var of type {self._var_type} does not support contains check."
  1003. )
  1004. if name == "reverse":
  1005. raise TypeError("Cannot reverse non-list var.")
  1006. if self._var_type is Any:
  1007. raise exceptions.UntypedVarError(
  1008. f"You must provide an annotation for the state var `{self!s}`. Annotation cannot be `{self._var_type}`."
  1009. )
  1010. raise VarAttributeError(
  1011. f"The State var has no attribute '{name}' or may have been annotated wrongly.",
  1012. )
  1013. def __bool__(self) -> bool:
  1014. """Raise exception if using Var in a boolean context.
  1015. Raises:
  1016. VarTypeError: when attempting to bool-ify the Var.
  1017. # noqa: DAR101 self
  1018. """
  1019. raise VarTypeError(
  1020. f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. "
  1021. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  1022. )
  1023. def __iter__(self) -> Any:
  1024. """Raise exception if using Var in an iterable context.
  1025. Raises:
  1026. VarTypeError: when attempting to iterate over the Var.
  1027. # noqa: DAR101 self
  1028. """
  1029. raise VarTypeError(
  1030. f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`."
  1031. )
  1032. def __contains__(self, _: Any) -> Var:
  1033. """Override the 'in' operator to alert the user that it is not supported.
  1034. Raises:
  1035. VarTypeError: the operation is not supported
  1036. # noqa: DAR101 self
  1037. """
  1038. raise VarTypeError(
  1039. "'in' operator not supported for Var types, use Var.contains() instead."
  1040. )
  1041. OUTPUT = TypeVar("OUTPUT", bound=Var)
  1042. VAR_SUBCLASS = TypeVar("VAR_SUBCLASS", bound=Var)
  1043. VAR_INSIDE = TypeVar("VAR_INSIDE")
  1044. class ToOperation:
  1045. """A var operation that converts a var to another type."""
  1046. def __getattr__(self, name: str) -> Any:
  1047. """Get an attribute of the var.
  1048. Args:
  1049. name: The name of the attribute.
  1050. Returns:
  1051. The attribute of the var.
  1052. """
  1053. from .object import ObjectVar
  1054. if isinstance(self, ObjectVar) and name != "_js_expr":
  1055. return ObjectVar.__getattr__(self, name)
  1056. return getattr(self._original, name)
  1057. def __post_init__(self):
  1058. """Post initialization."""
  1059. object.__delattr__(self, "_js_expr")
  1060. def __hash__(self) -> int:
  1061. """Calculate the hash value of the object.
  1062. Returns:
  1063. int: The hash value of the object.
  1064. """
  1065. return hash(self._original)
  1066. def _get_all_var_data(self) -> VarData | None:
  1067. """Get all the var data.
  1068. Returns:
  1069. The var data.
  1070. """
  1071. return VarData.merge(
  1072. self._original._get_all_var_data(),
  1073. self._var_data,
  1074. )
  1075. @classmethod
  1076. def create(
  1077. cls,
  1078. value: Var,
  1079. _var_type: GenericType | None = None,
  1080. _var_data: VarData | None = None,
  1081. ):
  1082. """Create a ToOperation.
  1083. Args:
  1084. value: The value of the var.
  1085. _var_type: The type of the Var.
  1086. _var_data: Additional hooks and imports associated with the Var.
  1087. Returns:
  1088. The ToOperation.
  1089. """
  1090. return cls(
  1091. _js_expr="", # pyright: ignore [reportCallIssue]
  1092. _var_data=_var_data, # pyright: ignore [reportCallIssue]
  1093. _var_type=_var_type or cls._default_var_type, # pyright: ignore [reportCallIssue, reportAttributeAccessIssue]
  1094. _original=value, # pyright: ignore [reportCallIssue]
  1095. )
  1096. class LiteralVar(Var):
  1097. """Base class for immutable literal vars."""
  1098. def __init_subclass__(cls, **kwargs):
  1099. """Initialize the subclass.
  1100. Args:
  1101. **kwargs: Additional keyword arguments.
  1102. Raises:
  1103. TypeError: If the LiteralVar subclass does not have a corresponding Var subclass.
  1104. """
  1105. super().__init_subclass__(**kwargs)
  1106. bases = cls.__bases__
  1107. bases_normalized = [
  1108. base if inspect.isclass(base) else get_origin(base) for base in bases
  1109. ]
  1110. possible_bases = [
  1111. base
  1112. for base in bases_normalized
  1113. if issubclass(base, Var) and base != LiteralVar
  1114. ]
  1115. if not possible_bases:
  1116. raise TypeError(
  1117. f"LiteralVar subclass {cls} must have a base class that is a subclass of Var and not LiteralVar."
  1118. )
  1119. var_subclasses = [
  1120. var_subclass
  1121. for var_subclass in _var_subclasses
  1122. if var_subclass.var_subclass in possible_bases
  1123. ]
  1124. if not var_subclasses:
  1125. raise TypeError(
  1126. f"LiteralVar {cls} must have a base class annotated with `python_types`."
  1127. )
  1128. if len(var_subclasses) != 1:
  1129. raise TypeError(
  1130. f"LiteralVar {cls} must have exactly one base class annotated with `python_types`."
  1131. )
  1132. var_subclass = var_subclasses[0]
  1133. # Remove the old subclass, happens because __init_subclass__ is called twice
  1134. # for each subclass. This is because of __slots__ in dataclasses.
  1135. for var_literal_subclass in list(_var_literal_subclasses):
  1136. if var_literal_subclass[1] is var_subclass:
  1137. _var_literal_subclasses.remove(var_literal_subclass)
  1138. _var_literal_subclasses.append((cls, var_subclass))
  1139. @classmethod
  1140. def create( # pyright: ignore [reportArgumentType]
  1141. cls,
  1142. value: Any,
  1143. _var_data: VarData | None = None,
  1144. ) -> Var:
  1145. """Create a var from a value.
  1146. Args:
  1147. value: The value to create the var from.
  1148. _var_data: Additional hooks and imports associated with the Var.
  1149. Returns:
  1150. The var.
  1151. Raises:
  1152. TypeError: If the value is not a supported type for LiteralVar.
  1153. """
  1154. from .object import LiteralObjectVar
  1155. from .sequence import ArrayVar, LiteralStringVar
  1156. if isinstance(value, Var):
  1157. if _var_data is None:
  1158. return value
  1159. return value._replace(merge_var_data=_var_data)
  1160. for literal_subclass, var_subclass in _var_literal_subclasses[::-1]:
  1161. if isinstance(value, var_subclass.python_types):
  1162. return literal_subclass.create(value, _var_data=_var_data)
  1163. from reflex.event import EventHandler
  1164. from reflex.utils.format import get_event_handler_parts
  1165. if isinstance(value, EventHandler):
  1166. return Var(_js_expr=".".join(filter(None, get_event_handler_parts(value))))
  1167. serialized_value = serializers.serialize(value)
  1168. if serialized_value is not None:
  1169. if isinstance(serialized_value, Mapping):
  1170. return LiteralObjectVar.create(
  1171. serialized_value,
  1172. _var_type=type(value),
  1173. _var_data=_var_data,
  1174. )
  1175. if isinstance(serialized_value, str):
  1176. return LiteralStringVar.create(
  1177. serialized_value, _var_type=type(value), _var_data=_var_data
  1178. )
  1179. return LiteralVar.create(serialized_value, _var_data=_var_data)
  1180. if isinstance(value, Base):
  1181. # get the fields of the pydantic class
  1182. fields = value.__fields__.keys()
  1183. one_level_dict = {field: getattr(value, field) for field in fields}
  1184. return LiteralObjectVar.create(
  1185. {
  1186. field: value
  1187. for field, value in one_level_dict.items()
  1188. if not callable(value)
  1189. },
  1190. _var_type=type(value),
  1191. _var_data=_var_data,
  1192. )
  1193. if dataclasses.is_dataclass(value) and not isinstance(value, type):
  1194. return LiteralObjectVar.create(
  1195. {
  1196. k: (None if callable(v) else v)
  1197. for k, v in dataclasses.asdict(value).items()
  1198. },
  1199. _var_type=type(value),
  1200. _var_data=_var_data,
  1201. )
  1202. if isinstance(value, range):
  1203. return ArrayVar.range(value.start, value.stop, value.step)
  1204. raise TypeError(
  1205. f"Unsupported type {type(value)} for LiteralVar. Tried to create a LiteralVar from {value}."
  1206. )
  1207. def __post_init__(self):
  1208. """Post-initialize the var."""
  1209. @property
  1210. def _var_value(self) -> Any:
  1211. raise NotImplementedError(
  1212. "LiteralVar subclasses must implement the _var_value property."
  1213. )
  1214. def json(self) -> str:
  1215. """Serialize the var to a JSON string.
  1216. Raises:
  1217. NotImplementedError: If the method is not implemented.
  1218. """
  1219. raise NotImplementedError(
  1220. "LiteralVar subclasses must implement the json method."
  1221. )
  1222. @serializers.serializer
  1223. def serialize_literal(value: LiteralVar):
  1224. """Serialize a Literal type.
  1225. Args:
  1226. value: The Literal to serialize.
  1227. Returns:
  1228. The serialized Literal.
  1229. """
  1230. return value._var_value
  1231. def get_python_literal(value: Union[LiteralVar, Any]) -> Any | None:
  1232. """Get the Python literal value.
  1233. Args:
  1234. value: The value to get the Python literal value of.
  1235. Returns:
  1236. The Python literal value.
  1237. """
  1238. if isinstance(value, LiteralVar):
  1239. return value._var_value
  1240. if isinstance(value, Var):
  1241. return None
  1242. return value
  1243. P = ParamSpec("P")
  1244. T = TypeVar("T")
  1245. # NoReturn is used to match CustomVarOperationReturn with no type hint.
  1246. @overload
  1247. def var_operation( # pyright: ignore [reportOverlappingOverload]
  1248. func: Callable[P, CustomVarOperationReturn[NoReturn]],
  1249. ) -> Callable[P, Var]: ...
  1250. @overload
  1251. def var_operation(
  1252. func: Callable[P, CustomVarOperationReturn[bool]],
  1253. ) -> Callable[P, BooleanVar]: ...
  1254. NUMBER_T = TypeVar("NUMBER_T", int, float, Union[int, float])
  1255. @overload
  1256. def var_operation(
  1257. func: Callable[P, CustomVarOperationReturn[NUMBER_T]],
  1258. ) -> Callable[P, NumberVar[NUMBER_T]]: ...
  1259. @overload
  1260. def var_operation(
  1261. func: Callable[P, CustomVarOperationReturn[str]],
  1262. ) -> Callable[P, StringVar]: ...
  1263. LIST_T = TypeVar("LIST_T", bound=Sequence)
  1264. @overload
  1265. def var_operation(
  1266. func: Callable[P, CustomVarOperationReturn[LIST_T]],
  1267. ) -> Callable[P, ArrayVar[LIST_T]]: ...
  1268. OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Mapping)
  1269. @overload
  1270. def var_operation(
  1271. func: Callable[P, CustomVarOperationReturn[OBJECT_TYPE]],
  1272. ) -> Callable[P, ObjectVar[OBJECT_TYPE]]: ...
  1273. @overload
  1274. def var_operation(
  1275. func: Callable[P, CustomVarOperationReturn[T]],
  1276. ) -> Callable[P, Var[T]]: ...
  1277. def var_operation( # pyright: ignore [reportInconsistentOverload]
  1278. func: Callable[P, CustomVarOperationReturn[T]],
  1279. ) -> Callable[P, Var[T]]:
  1280. """Decorator for creating a var operation.
  1281. Example:
  1282. ```python
  1283. @var_operation
  1284. def add(a: NumberVar, b: NumberVar):
  1285. return custom_var_operation(f"{a} + {b}")
  1286. ```
  1287. Args:
  1288. func: The function to decorate.
  1289. Returns:
  1290. The decorated function.
  1291. """
  1292. @functools.wraps(func)
  1293. def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]:
  1294. func_args = list(inspect.signature(func).parameters)
  1295. args_vars = {
  1296. func_args[i]: (LiteralVar.create(arg) if not isinstance(arg, Var) else arg)
  1297. for i, arg in enumerate(args)
  1298. }
  1299. kwargs_vars = {
  1300. key: LiteralVar.create(value) if not isinstance(value, Var) else value
  1301. for key, value in kwargs.items()
  1302. }
  1303. return CustomVarOperation.create(
  1304. name=func.__name__,
  1305. args=tuple(list(args_vars.items()) + list(kwargs_vars.items())),
  1306. return_var=func(*args_vars.values(), **kwargs_vars), # pyright: ignore [reportCallIssue, reportReturnType]
  1307. ).guess_type()
  1308. return wrapper
  1309. def figure_out_type(value: Any) -> types.GenericType:
  1310. """Figure out the type of the value.
  1311. Args:
  1312. value: The value to figure out the type of.
  1313. Returns:
  1314. The type of the value.
  1315. """
  1316. if isinstance(value, Var):
  1317. return value._var_type
  1318. type_ = type(value)
  1319. if has_args(type_):
  1320. return type_
  1321. if isinstance(value, list):
  1322. return List[unionize(*(figure_out_type(v) for v in value))]
  1323. if isinstance(value, set):
  1324. return Set[unionize(*(figure_out_type(v) for v in value))]
  1325. if isinstance(value, tuple):
  1326. return Tuple[unionize(*(figure_out_type(v) for v in value)), ...]
  1327. if isinstance(value, Mapping):
  1328. return Mapping[
  1329. unionize(*(figure_out_type(k) for k in value)),
  1330. unionize(*(figure_out_type(v) for v in value.values())),
  1331. ]
  1332. return type(value)
  1333. GLOBAL_CACHE = {}
  1334. class cached_property: # noqa: N801
  1335. """A cached property that caches the result of the function."""
  1336. def __init__(self, func: Callable):
  1337. """Initialize the cached_property.
  1338. Args:
  1339. func: The function to cache.
  1340. """
  1341. self._func = func
  1342. self._attrname = None
  1343. def __set_name__(self, owner: Any, name: str):
  1344. """Set the name of the cached property.
  1345. Args:
  1346. owner: The owner of the cached property.
  1347. name: The name of the cached property.
  1348. Raises:
  1349. TypeError: If the cached property is assigned to two different names.
  1350. """
  1351. if self._attrname is None:
  1352. self._attrname = name
  1353. original_del = getattr(owner, "__del__", None)
  1354. def delete_property(this: Any):
  1355. """Delete the cached property.
  1356. Args:
  1357. this: The object to delete the cached property from.
  1358. """
  1359. cached_field_name = "_reflex_cache_" + name
  1360. try:
  1361. unique_id = object.__getattribute__(this, cached_field_name)
  1362. except AttributeError:
  1363. if original_del is not None:
  1364. original_del(this)
  1365. return
  1366. if unique_id in GLOBAL_CACHE:
  1367. del GLOBAL_CACHE[unique_id]
  1368. if original_del is not None:
  1369. original_del(this)
  1370. owner.__del__ = delete_property
  1371. elif name != self._attrname:
  1372. raise TypeError(
  1373. "Cannot assign the same cached_property to two different names "
  1374. f"({self._attrname!r} and {name!r})."
  1375. )
  1376. def __get__(self, instance: Any, owner: Type | None = None):
  1377. """Get the cached property.
  1378. Args:
  1379. instance: The instance to get the cached property from.
  1380. owner: The owner of the cached property.
  1381. Returns:
  1382. The cached property.
  1383. Raises:
  1384. TypeError: If the class does not have __set_name__.
  1385. """
  1386. if self._attrname is None:
  1387. raise TypeError(
  1388. "Cannot use cached_property on a class without __set_name__."
  1389. )
  1390. cached_field_name = "_reflex_cache_" + self._attrname
  1391. try:
  1392. unique_id = object.__getattribute__(instance, cached_field_name)
  1393. except AttributeError:
  1394. unique_id = uuid.uuid4().int
  1395. object.__setattr__(instance, cached_field_name, unique_id)
  1396. if unique_id not in GLOBAL_CACHE:
  1397. GLOBAL_CACHE[unique_id] = self._func(instance)
  1398. return GLOBAL_CACHE[unique_id]
  1399. cached_property_no_lock = cached_property
  1400. class CachedVarOperation:
  1401. """Base class for cached var operations to lower boilerplate code."""
  1402. def __post_init__(self):
  1403. """Post-initialize the CachedVarOperation."""
  1404. object.__delattr__(self, "_js_expr")
  1405. def __getattr__(self, name: str) -> Any:
  1406. """Get an attribute of the var.
  1407. Args:
  1408. name: The name of the attribute.
  1409. Returns:
  1410. The attribute.
  1411. """
  1412. if name == "_js_expr":
  1413. return self._cached_var_name
  1414. parent_classes = inspect.getmro(type(self))
  1415. next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1]
  1416. return next_class.__getattr__(self, name)
  1417. def _get_all_var_data(self) -> VarData | None:
  1418. """Get all VarData associated with the Var.
  1419. Returns:
  1420. The VarData of the components and all of its children.
  1421. """
  1422. return self._cached_get_all_var_data
  1423. @cached_property_no_lock
  1424. def _cached_get_all_var_data(self) -> VarData | None:
  1425. """Get the cached VarData.
  1426. Returns:
  1427. The cached VarData.
  1428. """
  1429. return VarData.merge(
  1430. *(
  1431. value._get_all_var_data() if isinstance(value, Var) else None
  1432. for value in (
  1433. getattr(self, field.name)
  1434. for field in dataclasses.fields(self) # pyright: ignore [reportArgumentType]
  1435. )
  1436. ),
  1437. self._var_data,
  1438. )
  1439. def __hash__(self) -> int:
  1440. """Calculate the hash of the object.
  1441. Returns:
  1442. The hash of the object.
  1443. """
  1444. return hash(
  1445. (
  1446. type(self).__name__,
  1447. *[
  1448. getattr(self, field.name)
  1449. for field in dataclasses.fields(self) # pyright: ignore [reportArgumentType]
  1450. if field.name not in ["_js_expr", "_var_data", "_var_type"]
  1451. ],
  1452. )
  1453. )
  1454. def and_operation(a: Var | Any, b: Var | Any) -> Var:
  1455. """Perform a logical AND operation on two variables.
  1456. Args:
  1457. a: The first variable.
  1458. b: The second variable.
  1459. Returns:
  1460. The result of the logical AND operation.
  1461. """
  1462. return _and_operation(a, b)
  1463. @var_operation
  1464. def _and_operation(a: Var, b: Var):
  1465. """Perform a logical AND operation on two variables.
  1466. Args:
  1467. a: The first variable.
  1468. b: The second variable.
  1469. Returns:
  1470. The result of the logical AND operation.
  1471. """
  1472. return var_operation_return(
  1473. js_expression=f"({a} && {b})",
  1474. var_type=unionize(a._var_type, b._var_type),
  1475. )
  1476. def or_operation(a: Var | Any, b: Var | Any) -> Var:
  1477. """Perform a logical OR operation on two variables.
  1478. Args:
  1479. a: The first variable.
  1480. b: The second variable.
  1481. Returns:
  1482. The result of the logical OR operation.
  1483. """
  1484. return _or_operation(a, b)
  1485. @var_operation
  1486. def _or_operation(a: Var, b: Var):
  1487. """Perform a logical OR operation on two variables.
  1488. Args:
  1489. a: The first variable.
  1490. b: The second variable.
  1491. Returns:
  1492. The result of the logical OR operation.
  1493. """
  1494. return var_operation_return(
  1495. js_expression=f"({a} || {b})",
  1496. var_type=unionize(a._var_type, b._var_type),
  1497. )
  1498. @dataclasses.dataclass(
  1499. eq=False,
  1500. frozen=True,
  1501. slots=True,
  1502. )
  1503. class CallableVar(Var):
  1504. """Decorate a Var-returning function to act as both a Var and a function.
  1505. This is used as a compatibility shim for replacing Var objects in the
  1506. API with functions that return a family of Var.
  1507. """
  1508. fn: Callable[..., Var] = dataclasses.field(
  1509. default_factory=lambda: lambda: Var(_js_expr="undefined")
  1510. )
  1511. original_var: Var = dataclasses.field(
  1512. default_factory=lambda: Var(_js_expr="undefined")
  1513. )
  1514. def __init__(self, fn: Callable[..., Var]):
  1515. """Initialize a CallableVar.
  1516. Args:
  1517. fn: The function to decorate (must return Var)
  1518. """
  1519. original_var = fn()
  1520. super(CallableVar, self).__init__(
  1521. _js_expr=original_var._js_expr,
  1522. _var_type=original_var._var_type,
  1523. _var_data=VarData.merge(original_var._get_all_var_data()),
  1524. )
  1525. object.__setattr__(self, "fn", fn)
  1526. object.__setattr__(self, "original_var", original_var)
  1527. def __call__(self, *args: Any, **kwargs: Any) -> Var:
  1528. """Call the decorated function.
  1529. Args:
  1530. *args: The args to pass to the function.
  1531. **kwargs: The kwargs to pass to the function.
  1532. Returns:
  1533. The Var returned from calling the function.
  1534. """
  1535. return self.fn(*args, **kwargs)
  1536. def __hash__(self) -> int:
  1537. """Calculate the hash of the object.
  1538. Returns:
  1539. The hash of the object.
  1540. """
  1541. return hash((type(self).__name__, self.original_var))
  1542. RETURN_TYPE = TypeVar("RETURN_TYPE")
  1543. DICT_KEY = TypeVar("DICT_KEY")
  1544. DICT_VAL = TypeVar("DICT_VAL")
  1545. LIST_INSIDE = TypeVar("LIST_INSIDE")
  1546. class FakeComputedVarBaseClass(property):
  1547. """A fake base class for ComputedVar to avoid inheriting from property."""
  1548. __pydantic_run_validation__ = False
  1549. def is_computed_var(obj: Any) -> TypeGuard[ComputedVar]:
  1550. """Check if the object is a ComputedVar.
  1551. Args:
  1552. obj: The object to check.
  1553. Returns:
  1554. Whether the object is a ComputedVar.
  1555. """
  1556. return isinstance(obj, FakeComputedVarBaseClass)
  1557. @dataclasses.dataclass(
  1558. eq=False,
  1559. frozen=True,
  1560. slots=True,
  1561. )
  1562. class ComputedVar(Var[RETURN_TYPE]):
  1563. """A field with computed getters."""
  1564. # Whether to track dependencies and cache computed values
  1565. _cache: bool = dataclasses.field(default=False)
  1566. # Whether the computed var is a backend var
  1567. _backend: bool = dataclasses.field(default=False)
  1568. # The initial value of the computed var
  1569. _initial_value: RETURN_TYPE | types.Unset = dataclasses.field(default=types.Unset())
  1570. # Explicit var dependencies to track
  1571. _static_deps: dict[str | None, set[str]] = dataclasses.field(default_factory=dict)
  1572. # Whether var dependencies should be auto-determined
  1573. _auto_deps: bool = dataclasses.field(default=True)
  1574. # Interval at which the computed var should be updated
  1575. _update_interval: Optional[datetime.timedelta] = dataclasses.field(default=None)
  1576. _fget: Callable[[BaseState], RETURN_TYPE] = dataclasses.field(
  1577. default_factory=lambda: lambda _: None
  1578. ) # pyright: ignore [reportAssignmentType]
  1579. def __init__(
  1580. self,
  1581. fget: Callable[[BASE_STATE], RETURN_TYPE],
  1582. initial_value: RETURN_TYPE | types.Unset = types.Unset(),
  1583. cache: bool = True,
  1584. deps: Optional[List[Union[str, Var]]] = None,
  1585. auto_deps: bool = True,
  1586. interval: Optional[Union[int, datetime.timedelta]] = None,
  1587. backend: bool | None = None,
  1588. **kwargs,
  1589. ):
  1590. """Initialize a ComputedVar.
  1591. Args:
  1592. fget: The getter function.
  1593. initial_value: The initial value of the computed var.
  1594. cache: Whether to cache the computed value.
  1595. deps: Explicit var dependencies to track.
  1596. auto_deps: Whether var dependencies should be auto-determined.
  1597. interval: Interval at which the computed var should be updated.
  1598. backend: Whether the computed var is a backend var.
  1599. **kwargs: additional attributes to set on the instance
  1600. Raises:
  1601. TypeError: If the computed var dependencies are not Var instances or var names.
  1602. UntypedComputedVarError: If the computed var is untyped.
  1603. """
  1604. hint = kwargs.pop("return_type", None) or get_type_hints(fget).get(
  1605. "return", Any
  1606. )
  1607. if hint is Any:
  1608. raise UntypedComputedVarError(var_name=fget.__name__)
  1609. kwargs.setdefault("_js_expr", fget.__name__)
  1610. kwargs.setdefault("_var_type", hint)
  1611. Var.__init__(
  1612. self,
  1613. _js_expr=kwargs.pop("_js_expr"),
  1614. _var_type=kwargs.pop("_var_type"),
  1615. _var_data=kwargs.pop("_var_data", None),
  1616. )
  1617. if kwargs:
  1618. raise TypeError(f"Unexpected keyword arguments: {tuple(kwargs)}")
  1619. if backend is None:
  1620. backend = fget.__name__.startswith("_")
  1621. object.__setattr__(self, "_backend", backend)
  1622. object.__setattr__(self, "_initial_value", initial_value)
  1623. object.__setattr__(self, "_cache", cache)
  1624. if isinstance(interval, int):
  1625. interval = datetime.timedelta(seconds=interval)
  1626. object.__setattr__(self, "_update_interval", interval)
  1627. object.__setattr__(
  1628. self,
  1629. "_static_deps",
  1630. self._calculate_static_deps(deps),
  1631. )
  1632. object.__setattr__(self, "_auto_deps", auto_deps)
  1633. object.__setattr__(self, "_fget", fget)
  1634. def _calculate_static_deps(
  1635. self,
  1636. deps: Union[List[Union[str, Var]], dict[str | None, set[str]]] | None = None,
  1637. ) -> dict[str | None, set[str]]:
  1638. """Calculate the static dependencies of the computed var from user input or existing dependencies.
  1639. Args:
  1640. deps: The user input dependencies or existing dependencies.
  1641. Returns:
  1642. The static dependencies.
  1643. """
  1644. if isinstance(deps, dict):
  1645. # Assume a dict is coming from _replace, so no special processing.
  1646. return deps
  1647. _static_deps = {}
  1648. if deps is not None:
  1649. for dep in deps:
  1650. _static_deps = self._add_static_dep(dep, _static_deps)
  1651. return _static_deps
  1652. def _add_static_dep(
  1653. self, dep: Union[str, Var], deps: dict[str | None, set[str]] | None = None
  1654. ) -> dict[str | None, set[str]]:
  1655. """Add a static dependency to the computed var or existing dependency set.
  1656. Args:
  1657. dep: The dependency to add.
  1658. deps: The existing dependency set.
  1659. Returns:
  1660. The updated dependency set.
  1661. Raises:
  1662. TypeError: If the computed var dependencies are not Var instances or var names.
  1663. """
  1664. if deps is None:
  1665. deps = self._static_deps
  1666. if isinstance(dep, Var):
  1667. state_name = (
  1668. all_var_data.state
  1669. if (all_var_data := dep._get_all_var_data()) and all_var_data.state
  1670. else None
  1671. )
  1672. if all_var_data is not None:
  1673. var_name = all_var_data.field_name
  1674. else:
  1675. var_name = dep._js_expr
  1676. deps.setdefault(state_name, set()).add(var_name)
  1677. elif isinstance(dep, str) and dep != "":
  1678. deps.setdefault(None, set()).add(dep)
  1679. else:
  1680. raise TypeError(
  1681. "ComputedVar dependencies must be Var instances or var names (non-empty strings)."
  1682. )
  1683. return deps
  1684. @override
  1685. def _replace(
  1686. self,
  1687. merge_var_data: VarData | None = None,
  1688. **kwargs: Any,
  1689. ) -> Self:
  1690. """Replace the attributes of the ComputedVar.
  1691. Args:
  1692. merge_var_data: VarData to merge into the existing VarData.
  1693. **kwargs: Var fields to update.
  1694. Returns:
  1695. The new ComputedVar instance.
  1696. Raises:
  1697. TypeError: If kwargs contains keys that are not allowed.
  1698. """
  1699. if "deps" in kwargs:
  1700. kwargs["deps"] = self._calculate_static_deps(kwargs["deps"])
  1701. field_values = {
  1702. "fget": kwargs.pop("fget", self._fget),
  1703. "initial_value": kwargs.pop("initial_value", self._initial_value),
  1704. "cache": kwargs.pop("cache", self._cache),
  1705. "deps": kwargs.pop("deps", self._static_deps),
  1706. "auto_deps": kwargs.pop("auto_deps", self._auto_deps),
  1707. "interval": kwargs.pop("interval", self._update_interval),
  1708. "backend": kwargs.pop("backend", self._backend),
  1709. "_js_expr": kwargs.pop("_js_expr", self._js_expr),
  1710. "_var_type": kwargs.pop("_var_type", self._var_type),
  1711. "_var_data": kwargs.pop(
  1712. "_var_data", VarData.merge(self._var_data, merge_var_data)
  1713. ),
  1714. "return_type": kwargs.pop("return_type", self._var_type),
  1715. }
  1716. if kwargs:
  1717. unexpected_kwargs = ", ".join(kwargs.keys())
  1718. raise TypeError(f"Unexpected keyword arguments: {unexpected_kwargs}")
  1719. return type(self)(**field_values)
  1720. @property
  1721. def _cache_attr(self) -> str:
  1722. """Get the attribute used to cache the value on the instance.
  1723. Returns:
  1724. An attribute name.
  1725. """
  1726. return f"__cached_{self._js_expr}"
  1727. @property
  1728. def _last_updated_attr(self) -> str:
  1729. """Get the attribute used to store the last updated timestamp.
  1730. Returns:
  1731. An attribute name.
  1732. """
  1733. return f"__last_updated_{self._js_expr}"
  1734. def needs_update(self, instance: BaseState) -> bool:
  1735. """Check if the computed var needs to be updated.
  1736. Args:
  1737. instance: The state instance that the computed var is attached to.
  1738. Returns:
  1739. True if the computed var needs to be updated, False otherwise.
  1740. """
  1741. if self._update_interval is None:
  1742. return False
  1743. last_updated = getattr(instance, self._last_updated_attr, None)
  1744. if last_updated is None:
  1745. return True
  1746. return datetime.datetime.now() - last_updated > self._update_interval
  1747. @overload
  1748. def __get__(
  1749. self: ComputedVar[bool],
  1750. instance: None,
  1751. owner: Type,
  1752. ) -> BooleanVar: ...
  1753. @overload
  1754. def __get__(
  1755. self: ComputedVar[int] | ComputedVar[float],
  1756. instance: None,
  1757. owner: Type,
  1758. ) -> NumberVar: ...
  1759. @overload
  1760. def __get__(
  1761. self: ComputedVar[str],
  1762. instance: None,
  1763. owner: Type,
  1764. ) -> StringVar: ...
  1765. @overload
  1766. def __get__(
  1767. self: ComputedVar[MAPPING_TYPE],
  1768. instance: None,
  1769. owner: Type,
  1770. ) -> ObjectVar[MAPPING_TYPE]: ...
  1771. @overload
  1772. def __get__(
  1773. self: ComputedVar[list[LIST_INSIDE]],
  1774. instance: None,
  1775. owner: Type,
  1776. ) -> ArrayVar[list[LIST_INSIDE]]: ...
  1777. @overload
  1778. def __get__(
  1779. self: ComputedVar[tuple[LIST_INSIDE, ...]],
  1780. instance: None,
  1781. owner: Type,
  1782. ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
  1783. @overload
  1784. def __get__(
  1785. self: ComputedVar[BASE_TYPE],
  1786. instance: None,
  1787. owner: Type,
  1788. ) -> ObjectVar[BASE_TYPE]: ...
  1789. @overload
  1790. def __get__(
  1791. self: ComputedVar[SQLA_TYPE],
  1792. instance: None,
  1793. owner: Type,
  1794. ) -> ObjectVar[SQLA_TYPE]: ...
  1795. if TYPE_CHECKING:
  1796. @overload
  1797. def __get__(
  1798. self: ComputedVar[DATACLASS_TYPE], instance: None, owner: Any
  1799. ) -> ObjectVar[DATACLASS_TYPE]: ...
  1800. @overload
  1801. def __get__(self, instance: None, owner: Type) -> ComputedVar[RETURN_TYPE]: ...
  1802. @overload
  1803. def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ...
  1804. def __get__(self, instance: BaseState | None, owner: Type):
  1805. """Get the ComputedVar value.
  1806. If the value is already cached on the instance, return the cached value.
  1807. Args:
  1808. instance: the instance of the class accessing this computed var.
  1809. owner: the class that this descriptor is attached to.
  1810. Returns:
  1811. The value of the var for the given instance.
  1812. """
  1813. if instance is None:
  1814. state_where_defined = owner
  1815. while self._js_expr in state_where_defined.inherited_vars:
  1816. state_where_defined = state_where_defined.get_parent_state()
  1817. field_name = (
  1818. format_state_name(state_where_defined.get_full_name())
  1819. + "."
  1820. + self._js_expr
  1821. )
  1822. return dispatch(
  1823. field_name,
  1824. var_data=VarData.from_state(state_where_defined, self._js_expr),
  1825. result_var_type=self._var_type,
  1826. existing_var=self,
  1827. )
  1828. if not self._cache:
  1829. value = self.fget(instance)
  1830. else:
  1831. # handle caching
  1832. if not hasattr(instance, self._cache_attr) or self.needs_update(instance):
  1833. # Set cache attr on state instance.
  1834. setattr(instance, self._cache_attr, self.fget(instance))
  1835. # Ensure the computed var gets serialized to redis.
  1836. instance._was_touched = True
  1837. # Set the last updated timestamp on the state instance.
  1838. setattr(instance, self._last_updated_attr, datetime.datetime.now())
  1839. value = getattr(instance, self._cache_attr)
  1840. self._check_deprecated_return_type(instance, value)
  1841. return value
  1842. def _check_deprecated_return_type(self, instance: BaseState, value: Any) -> None:
  1843. if not _isinstance(value, self._var_type):
  1844. console.error(
  1845. f"Computed var '{type(instance).__name__}.{self._js_expr}' must return"
  1846. f" type '{self._var_type}', got '{type(value)}'."
  1847. )
  1848. def _deps(
  1849. self,
  1850. objclass: Type[BaseState],
  1851. obj: FunctionType | CodeType | None = None,
  1852. ) -> dict[str, set[str]]:
  1853. """Determine var dependencies of this ComputedVar.
  1854. Save references to attributes accessed on "self" or other fetched states.
  1855. Recursively called when the function makes a method call on "self" or
  1856. define comprehensions or nested functions that may reference "self".
  1857. Args:
  1858. objclass: the class obj this ComputedVar is attached to.
  1859. obj: the object to disassemble (defaults to the fget function).
  1860. Returns:
  1861. A dictionary mapping state names to the set of variable names
  1862. accessed by the given obj.
  1863. """
  1864. from .dep_tracking import DependencyTracker
  1865. d = {}
  1866. if self._static_deps:
  1867. d.update(self._static_deps)
  1868. # None is a placeholder for the current state class.
  1869. if None in d:
  1870. d[objclass.get_full_name()] = d.pop(None)
  1871. if not self._auto_deps:
  1872. return d
  1873. if obj is None:
  1874. fget = self._fget
  1875. if fget is not None:
  1876. obj = cast(FunctionType, fget)
  1877. else:
  1878. return d
  1879. try:
  1880. return DependencyTracker(
  1881. func=obj, state_cls=objclass, dependencies=d
  1882. ).dependencies
  1883. except Exception as e:
  1884. console.warn(
  1885. "Failed to automatically determine dependencies for computed var "
  1886. f"{objclass.__name__}.{self._js_expr}: {e}. "
  1887. "Provide static_deps and set auto_deps=False to suppress this warning."
  1888. )
  1889. return d
  1890. def mark_dirty(self, instance: BaseState) -> None:
  1891. """Mark this ComputedVar as dirty.
  1892. Args:
  1893. instance: the state instance that needs to recompute the value.
  1894. """
  1895. with contextlib.suppress(AttributeError):
  1896. delattr(instance, self._cache_attr)
  1897. def add_dependency(self, objclass: Type[BaseState], dep: Var):
  1898. """Explicitly add a dependency to the ComputedVar.
  1899. After adding the dependency, when the `dep` changes, this computed var
  1900. will be marked dirty.
  1901. Args:
  1902. objclass: The class obj this ComputedVar is attached to.
  1903. dep: The dependency to add.
  1904. Raises:
  1905. VarDependencyError: If the dependency is not a Var instance with a
  1906. state and field name
  1907. """
  1908. if all_var_data := dep._get_all_var_data():
  1909. state_name = all_var_data.state
  1910. if state_name:
  1911. var_name = all_var_data.field_name
  1912. if var_name:
  1913. self._static_deps.setdefault(state_name, set()).add(var_name)
  1914. objclass.get_root_state().get_class_substate(
  1915. state_name
  1916. )._var_dependencies.setdefault(var_name, set()).add(
  1917. (objclass.get_full_name(), self._js_expr)
  1918. )
  1919. return
  1920. raise VarDependencyError(
  1921. "ComputedVar dependencies must be Var instances with a state and "
  1922. f"field name, got {dep!r}."
  1923. )
  1924. def _determine_var_type(self) -> Type:
  1925. """Get the type of the var.
  1926. Returns:
  1927. The type of the var.
  1928. """
  1929. hints = get_type_hints(self._fget)
  1930. if "return" in hints:
  1931. return hints["return"]
  1932. return Any # pyright: ignore [reportReturnType]
  1933. @property
  1934. def __class__(self) -> Type:
  1935. """Get the class of the var.
  1936. Returns:
  1937. The class of the var.
  1938. """
  1939. return FakeComputedVarBaseClass
  1940. @property
  1941. def fget(self) -> Callable[[BaseState], RETURN_TYPE]:
  1942. """Get the getter function.
  1943. Returns:
  1944. The getter function.
  1945. """
  1946. return self._fget
  1947. class DynamicRouteVar(ComputedVar[Union[str, List[str]]]):
  1948. """A ComputedVar that represents a dynamic route."""
  1949. pass
  1950. async def _default_async_computed_var(_self: BaseState) -> Any:
  1951. return None
  1952. @dataclasses.dataclass(
  1953. eq=False,
  1954. frozen=True,
  1955. init=False,
  1956. slots=True,
  1957. )
  1958. class AsyncComputedVar(ComputedVar[RETURN_TYPE]):
  1959. """A computed var that wraps a coroutinefunction."""
  1960. _fget: Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]] = (
  1961. dataclasses.field(default=_default_async_computed_var)
  1962. )
  1963. @overload
  1964. def __get__(
  1965. self: AsyncComputedVar[bool],
  1966. instance: None,
  1967. owner: Type,
  1968. ) -> BooleanVar: ...
  1969. @overload
  1970. def __get__(
  1971. self: AsyncComputedVar[int] | ComputedVar[float],
  1972. instance: None,
  1973. owner: Type,
  1974. ) -> NumberVar: ...
  1975. @overload
  1976. def __get__(
  1977. self: AsyncComputedVar[str],
  1978. instance: None,
  1979. owner: Type,
  1980. ) -> StringVar: ...
  1981. @overload
  1982. def __get__(
  1983. self: AsyncComputedVar[MAPPING_TYPE],
  1984. instance: None,
  1985. owner: Type,
  1986. ) -> ObjectVar[MAPPING_TYPE]: ...
  1987. @overload
  1988. def __get__(
  1989. self: AsyncComputedVar[list[LIST_INSIDE]],
  1990. instance: None,
  1991. owner: Type,
  1992. ) -> ArrayVar[list[LIST_INSIDE]]: ...
  1993. @overload
  1994. def __get__(
  1995. self: AsyncComputedVar[tuple[LIST_INSIDE, ...]],
  1996. instance: None,
  1997. owner: Type,
  1998. ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
  1999. @overload
  2000. def __get__(
  2001. self: AsyncComputedVar[BASE_TYPE],
  2002. instance: None,
  2003. owner: Type,
  2004. ) -> ObjectVar[BASE_TYPE]: ...
  2005. @overload
  2006. def __get__(
  2007. self: AsyncComputedVar[SQLA_TYPE],
  2008. instance: None,
  2009. owner: Type,
  2010. ) -> ObjectVar[SQLA_TYPE]: ...
  2011. if TYPE_CHECKING:
  2012. @overload
  2013. def __get__(
  2014. self: AsyncComputedVar[DATACLASS_TYPE], instance: None, owner: Any
  2015. ) -> ObjectVar[DATACLASS_TYPE]: ...
  2016. @overload
  2017. def __get__(self, instance: None, owner: Type) -> AsyncComputedVar[RETURN_TYPE]: ...
  2018. @overload
  2019. def __get__(
  2020. self, instance: BaseState, owner: Type
  2021. ) -> Coroutine[None, None, RETURN_TYPE]: ...
  2022. def __get__(
  2023. self, instance: BaseState | None, owner
  2024. ) -> Var | Coroutine[None, None, RETURN_TYPE]:
  2025. """Get the ComputedVar value.
  2026. If the value is already cached on the instance, return the cached value.
  2027. Args:
  2028. instance: the instance of the class accessing this computed var.
  2029. owner: the class that this descriptor is attached to.
  2030. Returns:
  2031. The value of the var for the given instance.
  2032. """
  2033. if instance is None:
  2034. return super(AsyncComputedVar, self).__get__(instance, owner)
  2035. if not self._cache:
  2036. async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE:
  2037. value = await self.fget(instance)
  2038. self._check_deprecated_return_type(instance, value)
  2039. return value
  2040. return _awaitable_result()
  2041. else:
  2042. # handle caching
  2043. async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE:
  2044. if not hasattr(instance, self._cache_attr) or self.needs_update(
  2045. instance
  2046. ):
  2047. # Set cache attr on state instance.
  2048. setattr(instance, self._cache_attr, await self.fget(instance))
  2049. # Ensure the computed var gets serialized to redis.
  2050. instance._was_touched = True
  2051. # Set the last updated timestamp on the state instance.
  2052. setattr(instance, self._last_updated_attr, datetime.datetime.now())
  2053. value = getattr(instance, self._cache_attr)
  2054. self._check_deprecated_return_type(instance, value)
  2055. return value
  2056. return _awaitable_result()
  2057. @property
  2058. def fget(self) -> Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]]:
  2059. """Get the getter function.
  2060. Returns:
  2061. The getter function.
  2062. """
  2063. return self._fget
  2064. if TYPE_CHECKING:
  2065. BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
  2066. @overload
  2067. def computed_var(
  2068. fget: None = None,
  2069. initial_value: Any | types.Unset = types.Unset(),
  2070. cache: bool = True,
  2071. deps: Optional[List[Union[str, Var]]] = None,
  2072. auto_deps: bool = True,
  2073. interval: Optional[Union[datetime.timedelta, int]] = None,
  2074. backend: bool | None = None,
  2075. **kwargs,
  2076. ) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ... # pyright: ignore [reportInvalidTypeVarUse]
  2077. @overload
  2078. def computed_var(
  2079. fget: Callable[[BASE_STATE], RETURN_TYPE],
  2080. initial_value: RETURN_TYPE | types.Unset = types.Unset(),
  2081. cache: bool = True,
  2082. deps: Optional[List[Union[str, Var]]] = None,
  2083. auto_deps: bool = True,
  2084. interval: Optional[Union[datetime.timedelta, int]] = None,
  2085. backend: bool | None = None,
  2086. **kwargs,
  2087. ) -> ComputedVar[RETURN_TYPE]: ...
  2088. def computed_var(
  2089. fget: Callable[[BASE_STATE], Any] | None = None,
  2090. initial_value: Any | types.Unset = types.Unset(),
  2091. cache: bool = True,
  2092. deps: Optional[List[Union[str, Var]]] = None,
  2093. auto_deps: bool = True,
  2094. interval: Optional[Union[datetime.timedelta, int]] = None,
  2095. backend: bool | None = None,
  2096. **kwargs,
  2097. ) -> ComputedVar | Callable[[Callable[[BASE_STATE], Any]], ComputedVar]:
  2098. """A ComputedVar decorator with or without kwargs.
  2099. Args:
  2100. fget: The getter function.
  2101. initial_value: The initial value of the computed var.
  2102. cache: Whether to cache the computed value.
  2103. deps: Explicit var dependencies to track.
  2104. auto_deps: Whether var dependencies should be auto-determined.
  2105. interval: Interval at which the computed var should be updated.
  2106. backend: Whether the computed var is a backend var.
  2107. **kwargs: additional attributes to set on the instance
  2108. Returns:
  2109. A ComputedVar instance.
  2110. Raises:
  2111. ValueError: If caching is disabled and an update interval is set.
  2112. VarDependencyError: If user supplies dependencies without caching.
  2113. ComputedVarSignatureError: If the getter function has more than one argument.
  2114. """
  2115. if cache is False and interval is not None:
  2116. raise ValueError("Cannot set update interval without caching.")
  2117. if cache is False and (deps is not None or auto_deps is False):
  2118. raise VarDependencyError("Cannot track dependencies without caching.")
  2119. if fget is not None:
  2120. sign = inspect.signature(fget)
  2121. if len(sign.parameters) != 1:
  2122. raise ComputedVarSignatureError(fget.__name__, signature=str(sign))
  2123. if inspect.iscoroutinefunction(fget):
  2124. computed_var_cls = AsyncComputedVar
  2125. else:
  2126. computed_var_cls = ComputedVar
  2127. return computed_var_cls(
  2128. fget,
  2129. initial_value=initial_value,
  2130. cache=cache,
  2131. deps=deps,
  2132. auto_deps=auto_deps,
  2133. interval=interval,
  2134. backend=backend,
  2135. **kwargs,
  2136. )
  2137. def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar:
  2138. if inspect.iscoroutinefunction(fget):
  2139. computed_var_cls = AsyncComputedVar
  2140. else:
  2141. computed_var_cls = ComputedVar
  2142. return computed_var_cls(
  2143. fget,
  2144. initial_value=initial_value,
  2145. cache=cache,
  2146. deps=deps,
  2147. auto_deps=auto_deps,
  2148. interval=interval,
  2149. backend=backend,
  2150. **kwargs,
  2151. )
  2152. return wrapper
  2153. RETURN = TypeVar("RETURN")
  2154. class CustomVarOperationReturn(Var[RETURN]):
  2155. """Base class for custom var operations."""
  2156. @classmethod
  2157. def create(
  2158. cls,
  2159. js_expression: str,
  2160. _var_type: Type[RETURN] | None = None,
  2161. _var_data: VarData | None = None,
  2162. ) -> CustomVarOperationReturn[RETURN]:
  2163. """Create a CustomVarOperation.
  2164. Args:
  2165. js_expression: The JavaScript expression to evaluate.
  2166. _var_type: The type of the var.
  2167. _var_data: Additional hooks and imports associated with the Var.
  2168. Returns:
  2169. The CustomVarOperation.
  2170. """
  2171. return CustomVarOperationReturn(
  2172. _js_expr=js_expression,
  2173. _var_type=_var_type or Any,
  2174. _var_data=_var_data,
  2175. )
  2176. def var_operation_return(
  2177. js_expression: str,
  2178. var_type: Type[RETURN] | None = None,
  2179. var_data: VarData | None = None,
  2180. ) -> CustomVarOperationReturn[RETURN]:
  2181. """Shortcut for creating a CustomVarOperationReturn.
  2182. Args:
  2183. js_expression: The JavaScript expression to evaluate.
  2184. var_type: The type of the var.
  2185. var_data: Additional hooks and imports associated with the Var.
  2186. Returns:
  2187. The CustomVarOperationReturn.
  2188. """
  2189. return CustomVarOperationReturn.create(
  2190. js_expression,
  2191. var_type,
  2192. var_data,
  2193. )
  2194. @dataclasses.dataclass(
  2195. eq=False,
  2196. frozen=True,
  2197. slots=True,
  2198. )
  2199. class CustomVarOperation(CachedVarOperation, Var[T]):
  2200. """Base class for custom var operations."""
  2201. _name: str = dataclasses.field(default="")
  2202. _args: Tuple[Tuple[str, Var], ...] = dataclasses.field(default_factory=tuple)
  2203. _return: CustomVarOperationReturn[T] = dataclasses.field(
  2204. default_factory=lambda: CustomVarOperationReturn.create("")
  2205. )
  2206. @cached_property_no_lock
  2207. def _cached_var_name(self) -> str:
  2208. """Get the cached var name.
  2209. Returns:
  2210. The cached var name.
  2211. """
  2212. return str(self._return)
  2213. @cached_property_no_lock
  2214. def _cached_get_all_var_data(self) -> VarData | None:
  2215. """Get the cached VarData.
  2216. Returns:
  2217. The cached VarData.
  2218. """
  2219. return VarData.merge(
  2220. *(arg[1]._get_all_var_data() for arg in self._args),
  2221. self._return._get_all_var_data(),
  2222. self._var_data,
  2223. )
  2224. @classmethod
  2225. def create(
  2226. cls,
  2227. name: str,
  2228. args: Tuple[Tuple[str, Var], ...],
  2229. return_var: CustomVarOperationReturn[T],
  2230. _var_data: VarData | None = None,
  2231. ) -> CustomVarOperation[T]:
  2232. """Create a CustomVarOperation.
  2233. Args:
  2234. name: The name of the operation.
  2235. args: The arguments to the operation.
  2236. return_var: The return var.
  2237. _var_data: Additional hooks and imports associated with the Var.
  2238. Returns:
  2239. The CustomVarOperation.
  2240. """
  2241. return CustomVarOperation(
  2242. _js_expr="",
  2243. _var_type=return_var._var_type,
  2244. _var_data=_var_data,
  2245. _name=name,
  2246. _args=args,
  2247. _return=return_var,
  2248. )
  2249. class NoneVar(Var[None], python_types=type(None)):
  2250. """A var representing None."""
  2251. @dataclasses.dataclass(
  2252. eq=False,
  2253. frozen=True,
  2254. slots=True,
  2255. )
  2256. class LiteralNoneVar(LiteralVar, NoneVar):
  2257. """A var representing None."""
  2258. _var_value: None = None
  2259. def json(self) -> str:
  2260. """Serialize the var to a JSON string.
  2261. Returns:
  2262. The JSON string.
  2263. """
  2264. return "null"
  2265. @classmethod
  2266. def create(
  2267. cls,
  2268. value: None = None,
  2269. _var_data: VarData | None = None,
  2270. ) -> LiteralNoneVar:
  2271. """Create a var from a value.
  2272. Args:
  2273. value: The value of the var. Must be None. Existed for compatibility with LiteralVar.
  2274. _var_data: Additional hooks and imports associated with the Var.
  2275. Returns:
  2276. The var.
  2277. """
  2278. return LiteralNoneVar(
  2279. _js_expr="null",
  2280. _var_type=None,
  2281. _var_data=_var_data,
  2282. )
  2283. def get_to_operation(var_subclass: Type[Var]) -> Type[ToOperation]:
  2284. """Get the ToOperation class for a given Var subclass.
  2285. Args:
  2286. var_subclass: The Var subclass.
  2287. Returns:
  2288. The ToOperation class.
  2289. Raises:
  2290. ValueError: If the ToOperation class cannot be found.
  2291. """
  2292. possible_classes = [
  2293. saved_var_subclass.to_var_subclass
  2294. for saved_var_subclass in _var_subclasses
  2295. if saved_var_subclass.var_subclass is var_subclass
  2296. ]
  2297. if not possible_classes:
  2298. raise ValueError(f"Could not find ToOperation for {var_subclass}.")
  2299. return possible_classes[0]
  2300. @dataclasses.dataclass(
  2301. eq=False,
  2302. frozen=True,
  2303. slots=True,
  2304. )
  2305. class StateOperation(CachedVarOperation, Var):
  2306. """A var operation that accesses a field on an object."""
  2307. _state_name: str = dataclasses.field(default="")
  2308. _field: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  2309. @cached_property_no_lock
  2310. def _cached_var_name(self) -> str:
  2311. """Get the cached var name.
  2312. Returns:
  2313. The cached var name.
  2314. """
  2315. return f"{self._state_name!s}.{self._field!s}"
  2316. def __getattr__(self, name: str) -> Any:
  2317. """Get an attribute of the var.
  2318. Args:
  2319. name: The name of the attribute.
  2320. Returns:
  2321. The attribute.
  2322. """
  2323. if name == "_js_expr":
  2324. return self._cached_var_name
  2325. return getattr(self._field, name)
  2326. @classmethod
  2327. def create(
  2328. cls,
  2329. state_name: str,
  2330. field: Var,
  2331. _var_data: VarData | None = None,
  2332. ) -> StateOperation:
  2333. """Create a DotOperation.
  2334. Args:
  2335. state_name: The name of the state.
  2336. field: The field of the state.
  2337. _var_data: Additional hooks and imports associated with the Var.
  2338. Returns:
  2339. The DotOperation.
  2340. """
  2341. return StateOperation(
  2342. _js_expr="",
  2343. _var_type=field._var_type,
  2344. _var_data=_var_data,
  2345. _state_name=state_name,
  2346. _field=field,
  2347. )
  2348. def get_uuid_string_var() -> Var:
  2349. """Return a Var that generates a single memoized UUID via .web/utils/state.js.
  2350. useMemo with an empty dependency array ensures that the generated UUID is
  2351. consistent across re-renders of the component.
  2352. Returns:
  2353. A Var that generates a UUID at runtime.
  2354. """
  2355. from reflex.utils.imports import ImportVar
  2356. from reflex.vars import Var
  2357. unique_uuid_var = get_unique_variable_name()
  2358. unique_uuid_var_data = VarData(
  2359. imports={
  2360. f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # pyright: ignore [reportArgumentType]
  2361. "react": "useMemo",
  2362. },
  2363. hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
  2364. )
  2365. return Var(
  2366. _js_expr=unique_uuid_var,
  2367. _var_type=str,
  2368. _var_data=unique_uuid_var_data,
  2369. )
  2370. # Set of unique variable names.
  2371. USED_VARIABLES = set()
  2372. def get_unique_variable_name() -> str:
  2373. """Get a unique variable name.
  2374. Returns:
  2375. The unique variable name.
  2376. """
  2377. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  2378. if name not in USED_VARIABLES:
  2379. USED_VARIABLES.add(name)
  2380. return name
  2381. return get_unique_variable_name()
  2382. # Compile regex for finding reflex var tags.
  2383. _decode_var_pattern_re = (
  2384. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  2385. )
  2386. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  2387. # Defined global immutable vars.
  2388. _global_vars: Dict[int, Var] = {}
  2389. def _extract_var_data(value: Iterable) -> list[VarData | None]:
  2390. """Extract the var imports and hooks from an iterable containing a Var.
  2391. Args:
  2392. value: The iterable to extract the VarData from
  2393. Returns:
  2394. The extracted VarDatas.
  2395. """
  2396. from reflex.style import Style
  2397. from reflex.vars import Var
  2398. var_datas = []
  2399. with contextlib.suppress(TypeError):
  2400. for sub in value:
  2401. if isinstance(sub, Var):
  2402. var_datas.append(sub._var_data)
  2403. elif not isinstance(sub, str):
  2404. # Recurse into dict values.
  2405. if hasattr(sub, "values") and callable(sub.values):
  2406. var_datas.extend(_extract_var_data(sub.values())) # pyright: ignore [reportArgumentType]
  2407. # Recurse into iterable values (or dict keys).
  2408. var_datas.extend(_extract_var_data(sub))
  2409. # Style objects should already have _var_data.
  2410. if isinstance(value, Style):
  2411. var_datas.append(value._var_data)
  2412. else:
  2413. # Recurse when value is a dict itself.
  2414. values = getattr(value, "values", None)
  2415. if callable(values):
  2416. var_datas.extend(_extract_var_data(values())) # pyright: ignore [reportArgumentType]
  2417. return var_datas
  2418. dispatchers: Dict[GenericType, Callable[[Var], Var]] = {}
  2419. def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]:
  2420. """Register a function to transform a Var.
  2421. Args:
  2422. fn: The function to register.
  2423. Returns:
  2424. The decorator.
  2425. Raises:
  2426. TypeError: If the return type of the function is not a Var.
  2427. TypeError: If the Var return type does not have a generic type.
  2428. ValueError: If a function for the generic type is already registered.
  2429. """
  2430. return_type = fn.__annotations__["return"]
  2431. origin = get_origin(return_type)
  2432. if origin is not Var:
  2433. raise TypeError(
  2434. f"Expected return type of {fn.__name__} to be a Var, got {origin}."
  2435. )
  2436. generic_args = get_args(return_type)
  2437. if not generic_args:
  2438. raise TypeError(
  2439. f"Expected Var return type of {fn.__name__} to have a generic type."
  2440. )
  2441. generic_type = get_origin(generic_args[0]) or generic_args[0]
  2442. if generic_type in dispatchers:
  2443. raise ValueError(f"Function for {generic_type} already registered.")
  2444. dispatchers[generic_type] = fn
  2445. return fn
  2446. def generic_type_to_actual_type_map(
  2447. generic_type: GenericType, actual_type: GenericType
  2448. ) -> Dict[TypeVar, GenericType]:
  2449. """Map the generic type to the actual type.
  2450. Args:
  2451. generic_type: The generic type.
  2452. actual_type: The actual type.
  2453. Returns:
  2454. The mapping of type variables to actual types.
  2455. Raises:
  2456. TypeError: If the generic type and actual type do not match.
  2457. TypeError: If the number of generic arguments and actual arguments do not match.
  2458. """
  2459. generic_origin = get_origin(generic_type) or generic_type
  2460. actual_origin = get_origin(actual_type) or actual_type
  2461. if generic_origin is not actual_origin:
  2462. if isinstance(generic_origin, TypeVar):
  2463. return {generic_origin: actual_origin}
  2464. raise TypeError(
  2465. f"Type mismatch: expected {generic_origin}, got {actual_origin}."
  2466. )
  2467. generic_args = get_args(generic_type)
  2468. actual_args = get_args(actual_type)
  2469. if len(generic_args) != len(actual_args):
  2470. raise TypeError(
  2471. f"Number of generic arguments mismatch: expected {len(generic_args)}, got {len(actual_args)}."
  2472. )
  2473. # call recursively for nested generic types and merge the results
  2474. return {
  2475. k: v
  2476. for generic_arg, actual_arg in zip(generic_args, actual_args, strict=True)
  2477. for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items()
  2478. }
  2479. def resolve_generic_type_with_mapping(
  2480. generic_type: GenericType, type_mapping: Dict[TypeVar, GenericType]
  2481. ):
  2482. """Resolve a generic type with a type mapping.
  2483. Args:
  2484. generic_type: The generic type.
  2485. type_mapping: The type mapping.
  2486. Returns:
  2487. The resolved generic type.
  2488. """
  2489. if isinstance(generic_type, TypeVar):
  2490. return type_mapping.get(generic_type, generic_type)
  2491. generic_origin = get_origin(generic_type) or generic_type
  2492. generic_args = get_args(generic_type)
  2493. if not generic_args:
  2494. return generic_type
  2495. mapping_for_older_python = {
  2496. list: List,
  2497. set: Set,
  2498. dict: Dict,
  2499. tuple: Tuple,
  2500. frozenset: FrozenSet,
  2501. }
  2502. return mapping_for_older_python.get(generic_origin, generic_origin)[
  2503. tuple(
  2504. resolve_generic_type_with_mapping(arg, type_mapping) for arg in generic_args
  2505. )
  2506. ]
  2507. def resolve_arg_type_from_return_type(
  2508. arg_type: GenericType, return_type: GenericType, actual_return_type: GenericType
  2509. ) -> GenericType:
  2510. """Resolve the argument type from the return type.
  2511. Args:
  2512. arg_type: The argument type.
  2513. return_type: The return type.
  2514. actual_return_type: The requested return type.
  2515. Returns:
  2516. The argument type without the generics that are resolved.
  2517. """
  2518. return resolve_generic_type_with_mapping(
  2519. arg_type, generic_type_to_actual_type_map(return_type, actual_return_type)
  2520. )
  2521. def dispatch(
  2522. field_name: str,
  2523. var_data: VarData,
  2524. result_var_type: GenericType,
  2525. existing_var: Var | None = None,
  2526. ) -> Var:
  2527. """Dispatch a Var to the appropriate transformation function.
  2528. Args:
  2529. field_name: The name of the field.
  2530. var_data: The VarData associated with the Var.
  2531. result_var_type: The type of the Var.
  2532. existing_var: The existing Var to transform. Optional.
  2533. Returns:
  2534. The transformed Var.
  2535. Raises:
  2536. TypeError: If the return type of the function is not a Var.
  2537. TypeError: If the Var return type does not have a generic type.
  2538. TypeError: If the first argument of the function is not a Var.
  2539. TypeError: If the first argument of the function does not have a generic type
  2540. """
  2541. result_origin_var_type = get_origin(result_var_type) or result_var_type
  2542. if result_origin_var_type in dispatchers:
  2543. fn = dispatchers[result_origin_var_type]
  2544. fn_first_arg_type = next(
  2545. iter(inspect.signature(fn).parameters.values())
  2546. ).annotation
  2547. fn_return = inspect.signature(fn).return_annotation
  2548. fn_return_origin = get_origin(fn_return) or fn_return
  2549. if fn_return_origin is not Var:
  2550. raise TypeError(
  2551. f"Expected return type of {fn.__name__} to be a Var, got {fn_return}."
  2552. )
  2553. fn_return_generic_args = get_args(fn_return)
  2554. if not fn_return_generic_args:
  2555. raise TypeError(f"Expected generic type of {fn_return} to be a type.")
  2556. arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type
  2557. if arg_origin is not Var:
  2558. raise TypeError(
  2559. f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}."
  2560. )
  2561. arg_generic_args = get_args(fn_first_arg_type)
  2562. if not arg_generic_args:
  2563. raise TypeError(
  2564. f"Expected generic type of {fn_first_arg_type} to be a type."
  2565. )
  2566. arg_type = arg_generic_args[0]
  2567. fn_return_type = fn_return_generic_args[0]
  2568. var = (
  2569. Var(
  2570. field_name,
  2571. _var_data=var_data,
  2572. _var_type=resolve_arg_type_from_return_type(
  2573. arg_type, fn_return_type, result_var_type
  2574. ),
  2575. ).guess_type()
  2576. if existing_var is None
  2577. else existing_var._replace(
  2578. _var_type=resolve_arg_type_from_return_type(
  2579. arg_type, fn_return_type, result_var_type
  2580. ),
  2581. _var_data=var_data,
  2582. _js_expr=field_name,
  2583. ).guess_type()
  2584. )
  2585. return fn(var)
  2586. if existing_var is not None:
  2587. return existing_var._replace(
  2588. _js_expr=field_name,
  2589. _var_data=var_data,
  2590. _var_type=result_var_type,
  2591. ).guess_type()
  2592. return Var(
  2593. field_name,
  2594. _var_data=var_data,
  2595. _var_type=result_var_type,
  2596. ).guess_type()
  2597. V = TypeVar("V")
  2598. BASE_TYPE = TypeVar("BASE_TYPE", bound=Base | None)
  2599. SQLA_TYPE = TypeVar("SQLA_TYPE", bound=DeclarativeBase | None)
  2600. if TYPE_CHECKING:
  2601. from _typeshed import DataclassInstance
  2602. DATACLASS_TYPE = TypeVar("DATACLASS_TYPE", bound=DataclassInstance | None)
  2603. FIELD_TYPE = TypeVar("FIELD_TYPE")
  2604. MAPPING_TYPE = TypeVar("MAPPING_TYPE", bound=Mapping | None)
  2605. class Field(Generic[FIELD_TYPE]):
  2606. """Shadow class for Var to allow for type hinting in the IDE."""
  2607. def __set__(self, instance: Any, value: FIELD_TYPE):
  2608. """Set the Var.
  2609. Args:
  2610. instance: The instance of the class setting the Var.
  2611. value: The value to set the Var to.
  2612. """
  2613. @overload
  2614. def __get__(self: Field[bool], instance: None, owner: Any) -> BooleanVar: ...
  2615. @overload
  2616. def __get__(
  2617. self: Field[int] | Field[float] | Field[int | float], instance: None, owner: Any
  2618. ) -> NumberVar: ...
  2619. @overload
  2620. def __get__(self: Field[str], instance: None, owner: Any) -> StringVar: ...
  2621. @overload
  2622. def __get__(self: Field[None], instance: None, owner: Any) -> NoneVar: ...
  2623. @overload
  2624. def __get__(
  2625. self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]],
  2626. instance: None,
  2627. owner: Any,
  2628. ) -> ArrayVar[List[V]]: ...
  2629. @overload
  2630. def __get__(
  2631. self: Field[MAPPING_TYPE], instance: None, owner: Any
  2632. ) -> ObjectVar[MAPPING_TYPE]: ...
  2633. @overload
  2634. def __get__(
  2635. self: Field[BASE_TYPE], instance: None, owner: Any
  2636. ) -> ObjectVar[BASE_TYPE]: ...
  2637. @overload
  2638. def __get__(
  2639. self: Field[SQLA_TYPE], instance: None, owner: Any
  2640. ) -> ObjectVar[SQLA_TYPE]: ...
  2641. if TYPE_CHECKING:
  2642. @overload
  2643. def __get__(
  2644. self: Field[DATACLASS_TYPE], instance: None, owner: Any
  2645. ) -> ObjectVar[DATACLASS_TYPE]: ...
  2646. @overload
  2647. def __get__(self, instance: None, owner: Any) -> Var[FIELD_TYPE]: ...
  2648. @overload
  2649. def __get__(self, instance: Any, owner: Any) -> FIELD_TYPE: ...
  2650. def __get__(self, instance: Any, owner: Any): # pyright: ignore [reportInconsistentOverload]
  2651. """Get the Var.
  2652. Args:
  2653. instance: The instance of the class accessing the Var.
  2654. owner: The class that the Var is attached to.
  2655. """
  2656. def field(value: FIELD_TYPE) -> Field[FIELD_TYPE]:
  2657. """Create a Field with a value.
  2658. Args:
  2659. value: The value of the Field.
  2660. Returns:
  2661. The Field.
  2662. """
  2663. return value # pyright: ignore [reportReturnType]