base.py 99 KB

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