base.py 65 KB

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