base.py 101 KB

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