base.py 97 KB

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