base.py 76 KB

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