base.py 86 KB

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