base.py 76 KB

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