base.py 97 KB

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