1
0

base.py 107 KB

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