base.py 84 KB

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