1
0

base.py 75 KB

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