base.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822
  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 .function import FunctionVar, ToFunctionOperation
  316. from .number import (
  317. BooleanVar,
  318. NumberVar,
  319. ToBooleanVarOperation,
  320. ToNumberVarOperation,
  321. )
  322. from .object import ObjectVar, ToObjectOperation
  323. from .sequence import ArrayVar, StringVar, ToArrayOperation, ToStringOperation
  324. base_type = var_type
  325. if types.is_optional(base_type):
  326. base_type = types.get_args(base_type)[0]
  327. fixed_type = get_origin(base_type) or base_type
  328. fixed_output_type = get_origin(output) or output
  329. # If the first argument is a python type, we map it to the corresponding Var type.
  330. if fixed_output_type is dict:
  331. return self.to(ObjectVar, output)
  332. if fixed_output_type in (list, tuple, set):
  333. return self.to(ArrayVar, output)
  334. if fixed_output_type in (int, float):
  335. return self.to(NumberVar, output)
  336. if fixed_output_type is str:
  337. return self.to(StringVar, output)
  338. if fixed_output_type is bool:
  339. return self.to(BooleanVar, output)
  340. if fixed_output_type is None:
  341. return ToNoneOperation.create(self)
  342. if issubclass(fixed_output_type, Base):
  343. return self.to(ObjectVar, output)
  344. if dataclasses.is_dataclass(fixed_output_type) and not issubclass(
  345. fixed_output_type, Var
  346. ):
  347. return self.to(ObjectVar, output)
  348. if issubclass(output, BooleanVar):
  349. return ToBooleanVarOperation.create(self)
  350. if issubclass(output, NumberVar):
  351. if fixed_type is not None:
  352. if fixed_type is Union:
  353. inner_types = get_args(base_type)
  354. if not all(issubclass(t, (int, float)) for t in inner_types):
  355. raise TypeError(
  356. f"Unsupported type {var_type} for NumberVar. Must be int or float."
  357. )
  358. elif not issubclass(fixed_type, (int, float)):
  359. raise TypeError(
  360. f"Unsupported type {var_type} for NumberVar. Must be int or float."
  361. )
  362. return ToNumberVarOperation.create(self, var_type or float)
  363. if issubclass(output, ArrayVar):
  364. if fixed_type is not None and not issubclass(
  365. fixed_type, (list, tuple, set)
  366. ):
  367. raise TypeError(
  368. f"Unsupported type {var_type} for ArrayVar. Must be list, tuple, or set."
  369. )
  370. return ToArrayOperation.create(self, var_type or list)
  371. if issubclass(output, StringVar):
  372. return ToStringOperation.create(self, var_type or str)
  373. if issubclass(output, (ObjectVar, Base)):
  374. return ToObjectOperation.create(self, var_type or dict)
  375. if dataclasses.is_dataclass(output):
  376. return ToObjectOperation.create(self, var_type or dict)
  377. if issubclass(output, FunctionVar):
  378. # if fixed_type is not None and not issubclass(fixed_type, Callable):
  379. # raise TypeError(
  380. # f"Unsupported type {var_type} for FunctionVar. Must be Callable."
  381. # )
  382. return ToFunctionOperation.create(self, var_type or Callable)
  383. if issubclass(output, NoneVar):
  384. return ToNoneOperation.create(self)
  385. # If we can't determine the first argument, we just replace the _var_type.
  386. if not issubclass(output, Var) or var_type is None:
  387. return dataclasses.replace(
  388. self,
  389. _var_type=output,
  390. )
  391. # We couldn't determine the output type to be any other Var type, so we replace the _var_type.
  392. if var_type is not None:
  393. return dataclasses.replace(
  394. self,
  395. _var_type=var_type,
  396. )
  397. return self
  398. def guess_type(self) -> Var:
  399. """Guesses the type of the variable based on its `_var_type` attribute.
  400. Returns:
  401. Var: The guessed type of the variable.
  402. Raises:
  403. TypeError: If the type is not supported for guessing.
  404. """
  405. from .number import BooleanVar, NumberVar
  406. from .object import ObjectVar
  407. from .sequence import ArrayVar, StringVar
  408. var_type = self._var_type
  409. if var_type is None:
  410. return self.to(None)
  411. if types.is_optional(var_type):
  412. var_type = types.get_args(var_type)[0]
  413. if var_type is Any:
  414. return self
  415. fixed_type = get_origin(var_type) or var_type
  416. if fixed_type is Union:
  417. inner_types = get_args(var_type)
  418. if all(
  419. inspect.isclass(t) and issubclass(t, (int, float)) for t in inner_types
  420. ):
  421. return self.to(NumberVar, self._var_type)
  422. if all(
  423. inspect.isclass(t)
  424. and (issubclass(t, Base) or dataclasses.is_dataclass(t))
  425. for t in inner_types
  426. ):
  427. return self.to(ObjectVar, self._var_type)
  428. return self
  429. if not inspect.isclass(fixed_type):
  430. raise TypeError(f"Unsupported type {var_type} for guess_type.")
  431. if issubclass(fixed_type, bool):
  432. return self.to(BooleanVar, self._var_type)
  433. if issubclass(fixed_type, (int, float)):
  434. return self.to(NumberVar, self._var_type)
  435. if issubclass(fixed_type, dict):
  436. return self.to(ObjectVar, self._var_type)
  437. if issubclass(fixed_type, (list, tuple, set)):
  438. return self.to(ArrayVar, self._var_type)
  439. if issubclass(fixed_type, str):
  440. return self.to(StringVar, self._var_type)
  441. if issubclass(fixed_type, Base):
  442. return self.to(ObjectVar, self._var_type)
  443. if dataclasses.is_dataclass(fixed_type):
  444. return self.to(ObjectVar, self._var_type)
  445. return self
  446. def get_default_value(self) -> Any:
  447. """Get the default value of the var.
  448. Returns:
  449. The default value of the var.
  450. Raises:
  451. ImportError: If the var is a dataframe and pandas is not installed.
  452. """
  453. if types.is_optional(self._var_type):
  454. return None
  455. type_ = (
  456. get_origin(self._var_type)
  457. if types.is_generic_alias(self._var_type)
  458. else self._var_type
  459. )
  460. if type_ is Literal:
  461. args = get_args(self._var_type)
  462. return args[0] if args else None
  463. if issubclass(type_, str):
  464. return ""
  465. if issubclass(type_, types.get_args(Union[int, float])):
  466. return 0
  467. if issubclass(type_, bool):
  468. return False
  469. if issubclass(type_, list):
  470. return []
  471. if issubclass(type_, dict):
  472. return {}
  473. if issubclass(type_, tuple):
  474. return ()
  475. if types.is_dataframe(type_):
  476. try:
  477. import pandas as pd
  478. return pd.DataFrame()
  479. except ImportError as e:
  480. raise ImportError(
  481. "Please install pandas to use dataframes in your app."
  482. ) from e
  483. return set() if issubclass(type_, set) else None
  484. def get_setter_name(self, include_state: bool = True) -> str:
  485. """Get the name of the var's generated setter function.
  486. Args:
  487. include_state: Whether to include the state name in the setter name.
  488. Returns:
  489. The name of the setter function.
  490. """
  491. setter = constants.SETTER_PREFIX + self._var_field_name
  492. var_data = self._get_all_var_data()
  493. if var_data is None:
  494. return setter
  495. if not include_state or var_data.state == "":
  496. return setter
  497. return ".".join((var_data.state, setter))
  498. def get_setter(self) -> Callable[[BaseState, Any], None]:
  499. """Get the var's setter function.
  500. Returns:
  501. A function that that creates a setter for the var.
  502. """
  503. actual_name = self._var_field_name
  504. def setter(state: BaseState, value: Any):
  505. """Get the setter for the var.
  506. Args:
  507. state: The state within which we add the setter function.
  508. value: The value to set.
  509. """
  510. if self._var_type in [int, float]:
  511. try:
  512. value = self._var_type(value)
  513. setattr(state, actual_name, value)
  514. except ValueError:
  515. console.debug(
  516. f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
  517. )
  518. else:
  519. setattr(state, actual_name, value)
  520. setter.__qualname__ = self.get_setter_name()
  521. return setter
  522. def _var_set_state(self, state: type[BaseState] | str):
  523. """Set the state of the var.
  524. Args:
  525. state: The state to set.
  526. Returns:
  527. The var with the state set.
  528. """
  529. formatted_state_name = (
  530. state
  531. if isinstance(state, str)
  532. else format_state_name(state.get_full_name())
  533. )
  534. return StateOperation.create(
  535. formatted_state_name,
  536. self,
  537. _var_data=VarData.merge(
  538. VarData.from_state(state, self._js_expr), self._var_data
  539. ),
  540. ).guess_type()
  541. def __eq__(self, other: Var | Any) -> BooleanVar:
  542. """Check if the current variable is equal to the given variable.
  543. Args:
  544. other (Var | Any): The variable to compare with.
  545. Returns:
  546. BooleanVar: A BooleanVar object representing the result of the equality check.
  547. """
  548. from .number import equal_operation
  549. return equal_operation(self, other)
  550. def __ne__(self, other: Var | Any) -> BooleanVar:
  551. """Check if the current object is not equal to the given object.
  552. Parameters:
  553. other (Var | Any): The object to compare with.
  554. Returns:
  555. BooleanVar: A BooleanVar object representing the result of the comparison.
  556. """
  557. from .number import equal_operation
  558. return ~equal_operation(self, other)
  559. def bool(self) -> BooleanVar:
  560. """Convert the var to a boolean.
  561. Returns:
  562. The boolean var.
  563. """
  564. from .number import boolify
  565. return boolify(self)
  566. def __and__(self, other: Var | Any) -> Var:
  567. """Perform a logical AND operation on the current instance and another variable.
  568. Args:
  569. other: The variable to perform the logical AND operation with.
  570. Returns:
  571. A `BooleanVar` object representing the result of the logical AND operation.
  572. """
  573. return and_operation(self, other)
  574. def __rand__(self, other: Var | Any) -> Var:
  575. """Perform a logical AND operation on the current instance and another variable.
  576. Args:
  577. other: The variable to perform the logical AND operation with.
  578. Returns:
  579. A `BooleanVar` object representing the result of the logical AND operation.
  580. """
  581. return and_operation(other, self)
  582. def __or__(self, other: Var | Any) -> Var:
  583. """Perform a logical OR operation on the current instance and another variable.
  584. Args:
  585. other: The variable to perform the logical OR operation with.
  586. Returns:
  587. A `BooleanVar` object representing the result of the logical OR operation.
  588. """
  589. return or_operation(self, other)
  590. def __ror__(self, other: Var | Any) -> Var:
  591. """Perform a logical OR operation on the current instance and another variable.
  592. Args:
  593. other: The variable to perform the logical OR operation with.
  594. Returns:
  595. A `BooleanVar` object representing the result of the logical OR operation.
  596. """
  597. return or_operation(other, self)
  598. def __invert__(self) -> BooleanVar:
  599. """Perform a logical NOT operation on the current instance.
  600. Returns:
  601. A `BooleanVar` object representing the result of the logical NOT operation.
  602. """
  603. return ~self.bool()
  604. def to_string(self):
  605. """Convert the var to a string.
  606. Returns:
  607. The string var.
  608. """
  609. from .function import JSON_STRINGIFY
  610. from .sequence import StringVar
  611. return JSON_STRINGIFY.call(self).to(StringVar)
  612. def as_ref(self) -> Var:
  613. """Get a reference to the var.
  614. Returns:
  615. The reference to the var.
  616. """
  617. from .object import ObjectVar
  618. refs = Var(
  619. _js_expr="refs",
  620. _var_data=VarData(
  621. imports={
  622. f"/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
  623. }
  624. ),
  625. ).to(ObjectVar, Dict[str, str])
  626. return refs[LiteralVar.create(str(self))]
  627. @deprecated("Use `.js_type()` instead.")
  628. def _type(self) -> StringVar:
  629. """Returns the type of the object.
  630. This method uses the `typeof` function from the `FunctionStringVar` class
  631. to determine the type of the object.
  632. Returns:
  633. StringVar: A string variable representing the type of the object.
  634. """
  635. return self.js_type()
  636. def js_type(self) -> StringVar:
  637. """Returns the javascript type of the object.
  638. This method uses the `typeof` function from the `FunctionStringVar` class
  639. to determine the type of the object.
  640. Returns:
  641. StringVar: A string variable representing the type of the object.
  642. """
  643. from .function import FunctionStringVar
  644. from .sequence import StringVar
  645. type_of = FunctionStringVar("typeof")
  646. return type_of.call(self).to(StringVar)
  647. def without_data(self):
  648. """Create a copy of the var without the data.
  649. Returns:
  650. The var without the data.
  651. """
  652. return dataclasses.replace(self, _var_data=None)
  653. def contains(self, value: Any = None, field: Any = None):
  654. """Get an attribute of the var.
  655. Args:
  656. value: The value to check for.
  657. field: The field to check for.
  658. Raises:
  659. TypeError: If the var does not support contains check.
  660. """
  661. raise TypeError(
  662. f"Var of type {self._var_type} does not support contains check."
  663. )
  664. def __get__(self, instance: Any, owner: Any):
  665. """Get the var.
  666. Args:
  667. instance: The instance to get the var from.
  668. owner: The owner of the var.
  669. Returns:
  670. The var.
  671. """
  672. return self
  673. def reverse(self):
  674. """Reverse the var.
  675. Raises:
  676. TypeError: If the var does not support reverse.
  677. """
  678. raise TypeError("Cannot reverse non-list var.")
  679. def __getattr__(self, name: str):
  680. """Get an attribute of the var.
  681. Args:
  682. name: The name of the attribute.
  683. Returns:
  684. The attribute.
  685. Raises:
  686. VarAttributeError: If the attribute does not exist.
  687. TypeError: If the var type is Any.
  688. """
  689. if name.startswith("_"):
  690. return self.__getattribute__(name)
  691. if self._var_type is Any:
  692. raise TypeError(
  693. f"You must provide an annotation for the state var `{str(self)}`. Annotation cannot be `{self._var_type}`."
  694. )
  695. if name in REPLACED_NAMES:
  696. raise VarAttributeError(
  697. f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
  698. )
  699. raise VarAttributeError(
  700. f"The State var has no attribute '{name}' or may have been annotated wrongly.",
  701. )
  702. def _decode(self) -> Any:
  703. """Decode Var as a python value.
  704. Note that Var with state set cannot be decoded python-side and will be
  705. returned as full_name.
  706. Returns:
  707. The decoded value or the Var name.
  708. """
  709. if isinstance(self, LiteralVar):
  710. return self._var_value # type: ignore
  711. try:
  712. return json.loads(str(self))
  713. except ValueError:
  714. try:
  715. return json.loads(self.json())
  716. except (ValueError, NotImplementedError):
  717. return str(self)
  718. @property
  719. def _var_state(self) -> str:
  720. """Compat method for getting the state.
  721. Returns:
  722. The state name associated with the var.
  723. """
  724. var_data = self._get_all_var_data()
  725. return var_data.state if var_data else ""
  726. @overload
  727. @classmethod
  728. def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
  729. @overload
  730. @classmethod
  731. def range(
  732. cls,
  733. start: int | NumberVar,
  734. end: int | NumberVar,
  735. step: int | NumberVar = 1,
  736. /,
  737. ) -> ArrayVar[List[int]]: ...
  738. @classmethod
  739. def range(
  740. cls,
  741. first_endpoint: int | NumberVar,
  742. second_endpoint: int | NumberVar | None = None,
  743. step: int | NumberVar | None = None,
  744. ) -> ArrayVar[List[int]]:
  745. """Create a range of numbers.
  746. Args:
  747. first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
  748. second_endpoint: The end of the range.
  749. step: The step of the range.
  750. Returns:
  751. The range of numbers.
  752. """
  753. from .sequence import ArrayVar
  754. return ArrayVar.range(first_endpoint, second_endpoint, step)
  755. def __bool__(self) -> bool:
  756. """Raise exception if using Var in a boolean context.
  757. Raises:
  758. VarTypeError: when attempting to bool-ify the Var.
  759. """
  760. raise VarTypeError(
  761. f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. "
  762. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  763. )
  764. def __iter__(self) -> Any:
  765. """Raise exception if using Var in an iterable context.
  766. Raises:
  767. VarTypeError: when attempting to iterate over the Var.
  768. """
  769. raise VarTypeError(
  770. f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`."
  771. )
  772. def __contains__(self, _: Any) -> Var:
  773. """Override the 'in' operator to alert the user that it is not supported.
  774. Raises:
  775. VarTypeError: the operation is not supported
  776. """
  777. raise VarTypeError(
  778. "'in' operator not supported for Var types, use Var.contains() instead."
  779. )
  780. def json(self) -> str:
  781. """Serialize the var to a JSON string.
  782. Raises:
  783. NotImplementedError: If the method is not implemented.
  784. """
  785. raise NotImplementedError("Var subclasses must implement the json method.")
  786. OUTPUT = TypeVar("OUTPUT", bound=Var)
  787. class LiteralVar(Var):
  788. """Base class for immutable literal vars."""
  789. @classmethod
  790. def create(
  791. cls,
  792. value: Any,
  793. _var_data: VarData | None = None,
  794. ) -> Var:
  795. """Create a var from a value.
  796. Args:
  797. value: The value to create the var from.
  798. _var_data: Additional hooks and imports associated with the Var.
  799. Returns:
  800. The var.
  801. Raises:
  802. TypeError: If the value is not a supported type for LiteralVar.
  803. """
  804. from .number import LiteralBooleanVar, LiteralNumberVar
  805. from .object import LiteralObjectVar
  806. from .sequence import LiteralArrayVar, LiteralStringVar
  807. if isinstance(value, Var):
  808. if _var_data is None:
  809. return value
  810. return value._replace(merge_var_data=_var_data)
  811. if isinstance(value, str):
  812. return LiteralStringVar.create(value, _var_data=_var_data)
  813. if isinstance(value, bool):
  814. return LiteralBooleanVar.create(value, _var_data=_var_data)
  815. if isinstance(value, (int, float)):
  816. return LiteralNumberVar.create(value, _var_data=_var_data)
  817. if isinstance(value, dict):
  818. return LiteralObjectVar.create(value, _var_data=_var_data)
  819. if isinstance(value, (list, tuple, set)):
  820. return LiteralArrayVar.create(value, _var_data=_var_data)
  821. if value is None:
  822. return LiteralNoneVar.create(_var_data=_var_data)
  823. from reflex.event import EventChain, EventHandler, EventSpec
  824. from reflex.utils.format import get_event_handler_parts
  825. from .function import ArgsFunctionOperation, FunctionStringVar
  826. from .object import LiteralObjectVar
  827. if isinstance(value, EventSpec):
  828. event_name = LiteralVar.create(
  829. ".".join(filter(None, get_event_handler_parts(value.handler)))
  830. )
  831. event_args = LiteralVar.create(
  832. {str(name): value for name, value in value.args}
  833. )
  834. event_client_name = LiteralVar.create(value.client_handler_name)
  835. return FunctionStringVar("Event").call(
  836. event_name,
  837. event_args,
  838. *([event_client_name] if value.client_handler_name else []),
  839. )
  840. if isinstance(value, EventChain):
  841. sig = inspect.signature(value.args_spec) # type: ignore
  842. if sig.parameters:
  843. arg_def = tuple((f"_{p}" for p in sig.parameters))
  844. arg_def_expr = LiteralVar.create([Var(_js_expr=arg) for arg in arg_def])
  845. else:
  846. # add a default argument for addEvents if none were specified in value.args_spec
  847. # used to trigger the preventDefault() on the event.
  848. arg_def = ("...args",)
  849. arg_def_expr = Var(_js_expr="args")
  850. return ArgsFunctionOperation.create(
  851. arg_def,
  852. FunctionStringVar.create("addEvents").call(
  853. LiteralVar.create(
  854. [LiteralVar.create(event) for event in value.events]
  855. ),
  856. arg_def_expr,
  857. LiteralVar.create(value.event_actions),
  858. ),
  859. )
  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 serializers.serialize(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. hints = get_type_hints(fget)
  1232. hint = hints.get("return", Any)
  1233. kwargs["_js_expr"] = kwargs.pop("_js_expr", fget.__name__)
  1234. kwargs["_var_type"] = kwargs.pop("_var_type", hint)
  1235. Var.__init__(
  1236. self,
  1237. _js_expr=kwargs.pop("_js_expr"),
  1238. _var_type=kwargs.pop("_var_type"),
  1239. _var_data=kwargs.pop("_var_data", None),
  1240. )
  1241. if backend is None:
  1242. backend = fget.__name__.startswith("_")
  1243. object.__setattr__(self, "_backend", backend)
  1244. object.__setattr__(self, "_initial_value", initial_value)
  1245. object.__setattr__(self, "_cache", cache)
  1246. if isinstance(interval, int):
  1247. interval = datetime.timedelta(seconds=interval)
  1248. object.__setattr__(self, "_update_interval", interval)
  1249. if deps is None:
  1250. deps = []
  1251. else:
  1252. for dep in deps:
  1253. if isinstance(dep, Var):
  1254. continue
  1255. if isinstance(dep, str) and dep != "":
  1256. continue
  1257. raise TypeError(
  1258. "ComputedVar dependencies must be Var instances or var names (non-empty strings)."
  1259. )
  1260. object.__setattr__(
  1261. self,
  1262. "_static_deps",
  1263. {dep._js_expr if isinstance(dep, Var) else dep for dep in deps},
  1264. )
  1265. object.__setattr__(self, "_auto_deps", auto_deps)
  1266. object.__setattr__(self, "_fget", fget)
  1267. @override
  1268. def _replace(self, merge_var_data=None, **kwargs: Any) -> Self:
  1269. """Replace the attributes of the ComputedVar.
  1270. Args:
  1271. merge_var_data: VarData to merge into the existing VarData.
  1272. **kwargs: Var fields to update.
  1273. Returns:
  1274. The new ComputedVar instance.
  1275. Raises:
  1276. TypeError: If kwargs contains keys that are not allowed.
  1277. """
  1278. field_values = dict(
  1279. fget=kwargs.pop("fget", self._fget),
  1280. initial_value=kwargs.pop("initial_value", self._initial_value),
  1281. cache=kwargs.pop("cache", self._cache),
  1282. deps=kwargs.pop("deps", self._static_deps),
  1283. auto_deps=kwargs.pop("auto_deps", self._auto_deps),
  1284. interval=kwargs.pop("interval", self._update_interval),
  1285. backend=kwargs.pop("backend", self._backend),
  1286. _js_expr=kwargs.pop("_js_expr", self._js_expr),
  1287. _var_type=kwargs.pop("_var_type", self._var_type),
  1288. _var_data=kwargs.pop(
  1289. "_var_data", VarData.merge(self._var_data, merge_var_data)
  1290. ),
  1291. )
  1292. if kwargs:
  1293. unexpected_kwargs = ", ".join(kwargs.keys())
  1294. raise TypeError(f"Unexpected keyword arguments: {unexpected_kwargs}")
  1295. return type(self)(**field_values)
  1296. @property
  1297. def _cache_attr(self) -> str:
  1298. """Get the attribute used to cache the value on the instance.
  1299. Returns:
  1300. An attribute name.
  1301. """
  1302. return f"__cached_{self._js_expr}"
  1303. @property
  1304. def _last_updated_attr(self) -> str:
  1305. """Get the attribute used to store the last updated timestamp.
  1306. Returns:
  1307. An attribute name.
  1308. """
  1309. return f"__last_updated_{self._js_expr}"
  1310. def needs_update(self, instance: BaseState) -> bool:
  1311. """Check if the computed var needs to be updated.
  1312. Args:
  1313. instance: The state instance that the computed var is attached to.
  1314. Returns:
  1315. True if the computed var needs to be updated, False otherwise.
  1316. """
  1317. if self._update_interval is None:
  1318. return False
  1319. last_updated = getattr(instance, self._last_updated_attr, None)
  1320. if last_updated is None:
  1321. return True
  1322. return datetime.datetime.now() - last_updated > self._update_interval
  1323. @overload
  1324. def __get__(
  1325. self: ComputedVar[int] | ComputedVar[float],
  1326. instance: None,
  1327. owner: Type,
  1328. ) -> NumberVar: ...
  1329. @overload
  1330. def __get__(
  1331. self: ComputedVar[str],
  1332. instance: None,
  1333. owner: Type,
  1334. ) -> StringVar: ...
  1335. @overload
  1336. def __get__(
  1337. self: ComputedVar[dict[DICT_KEY, DICT_VAL]],
  1338. instance: None,
  1339. owner: Type,
  1340. ) -> ObjectVar[dict[DICT_KEY, DICT_VAL]]: ...
  1341. @overload
  1342. def __get__(
  1343. self: ComputedVar[list[LIST_INSIDE]],
  1344. instance: None,
  1345. owner: Type,
  1346. ) -> ArrayVar[list[LIST_INSIDE]]: ...
  1347. @overload
  1348. def __get__(
  1349. self: ComputedVar[set[LIST_INSIDE]],
  1350. instance: None,
  1351. owner: Type,
  1352. ) -> ArrayVar[set[LIST_INSIDE]]: ...
  1353. @overload
  1354. def __get__(
  1355. self: ComputedVar[tuple[LIST_INSIDE, ...]],
  1356. instance: None,
  1357. owner: Type,
  1358. ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
  1359. @overload
  1360. def __get__(self, instance: None, owner: Type) -> ComputedVar[RETURN_TYPE]: ...
  1361. @overload
  1362. def __get__(self, instance: BaseState, owner: Type) -> RETURN_TYPE: ...
  1363. def __get__(self, instance: BaseState | None, owner):
  1364. """Get the ComputedVar value.
  1365. If the value is already cached on the instance, return the cached value.
  1366. Args:
  1367. instance: the instance of the class accessing this computed var.
  1368. owner: the class that this descriptor is attached to.
  1369. Returns:
  1370. The value of the var for the given instance.
  1371. """
  1372. if instance is None:
  1373. state_where_defined = owner
  1374. while self._js_expr in state_where_defined.inherited_vars:
  1375. state_where_defined = state_where_defined.get_parent_state()
  1376. field_name = (
  1377. format_state_name(state_where_defined.get_full_name())
  1378. + "."
  1379. + self._js_expr
  1380. )
  1381. return dispatch(
  1382. field_name,
  1383. var_data=VarData.from_state(state_where_defined, self._js_expr),
  1384. result_var_type=self._var_type,
  1385. existing_var=self,
  1386. )
  1387. if not self._cache:
  1388. return self.fget(instance)
  1389. # handle caching
  1390. if not hasattr(instance, self._cache_attr) or self.needs_update(instance):
  1391. # Set cache attr on state instance.
  1392. setattr(instance, self._cache_attr, self.fget(instance))
  1393. # Ensure the computed var gets serialized to redis.
  1394. instance._was_touched = True
  1395. # Set the last updated timestamp on the state instance.
  1396. setattr(instance, self._last_updated_attr, datetime.datetime.now())
  1397. return getattr(instance, self._cache_attr)
  1398. def _deps(
  1399. self,
  1400. objclass: Type,
  1401. obj: FunctionType | CodeType | None = None,
  1402. self_name: Optional[str] = None,
  1403. ) -> set[str]:
  1404. """Determine var dependencies of this ComputedVar.
  1405. Save references to attributes accessed on "self". Recursively called
  1406. when the function makes a method call on "self" or define comprehensions
  1407. or nested functions that may reference "self".
  1408. Args:
  1409. objclass: the class obj this ComputedVar is attached to.
  1410. obj: the object to disassemble (defaults to the fget function).
  1411. self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
  1412. Returns:
  1413. A set of variable names accessed by the given obj.
  1414. Raises:
  1415. VarValueError: if the function references the get_state, parent_state, or substates attributes
  1416. (cannot track deps in a related state, only implicitly via parent state).
  1417. """
  1418. if not self._auto_deps:
  1419. return self._static_deps
  1420. d = self._static_deps.copy()
  1421. if obj is None:
  1422. fget = self._fget
  1423. if fget is not None:
  1424. obj = cast(FunctionType, fget)
  1425. else:
  1426. return set()
  1427. with contextlib.suppress(AttributeError):
  1428. # unbox functools.partial
  1429. obj = cast(FunctionType, obj.func) # type: ignore
  1430. with contextlib.suppress(AttributeError):
  1431. # unbox EventHandler
  1432. obj = cast(FunctionType, obj.fn) # type: ignore
  1433. if self_name is None and isinstance(obj, FunctionType):
  1434. try:
  1435. # the first argument to the function is the name of "self" arg
  1436. self_name = obj.__code__.co_varnames[0]
  1437. except (AttributeError, IndexError):
  1438. self_name = None
  1439. if self_name is None:
  1440. # cannot reference attributes on self if method takes no args
  1441. return set()
  1442. invalid_names = ["get_state", "parent_state", "substates", "get_substate"]
  1443. self_is_top_of_stack = False
  1444. for instruction in dis.get_instructions(obj):
  1445. if (
  1446. instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
  1447. and instruction.argval == self_name
  1448. ):
  1449. # bytecode loaded the class instance to the top of stack, next load instruction
  1450. # is referencing an attribute on self
  1451. self_is_top_of_stack = True
  1452. continue
  1453. if self_is_top_of_stack and instruction.opname in (
  1454. "LOAD_ATTR",
  1455. "LOAD_METHOD",
  1456. ):
  1457. try:
  1458. ref_obj = getattr(objclass, instruction.argval)
  1459. except Exception:
  1460. ref_obj = None
  1461. if instruction.argval in invalid_names:
  1462. raise VarValueError(
  1463. f"Cached var {str(self)} cannot access arbitrary state via `{instruction.argval}`."
  1464. )
  1465. if callable(ref_obj):
  1466. # recurse into callable attributes
  1467. d.update(
  1468. self._deps(
  1469. objclass=objclass,
  1470. obj=ref_obj,
  1471. )
  1472. )
  1473. # recurse into property fget functions
  1474. elif isinstance(ref_obj, property) and not isinstance(
  1475. ref_obj, ComputedVar
  1476. ):
  1477. d.update(
  1478. self._deps(
  1479. objclass=objclass,
  1480. obj=ref_obj.fget, # type: ignore
  1481. )
  1482. )
  1483. elif (
  1484. instruction.argval in objclass.backend_vars
  1485. or instruction.argval in objclass.vars
  1486. ):
  1487. # var access
  1488. d.add(instruction.argval)
  1489. elif instruction.opname == "LOAD_CONST" and isinstance(
  1490. instruction.argval, CodeType
  1491. ):
  1492. # recurse into nested functions / comprehensions, which can reference
  1493. # instance attributes from the outer scope
  1494. d.update(
  1495. self._deps(
  1496. objclass=objclass,
  1497. obj=instruction.argval,
  1498. self_name=self_name,
  1499. )
  1500. )
  1501. self_is_top_of_stack = False
  1502. return d
  1503. def mark_dirty(self, instance) -> None:
  1504. """Mark this ComputedVar as dirty.
  1505. Args:
  1506. instance: the state instance that needs to recompute the value.
  1507. """
  1508. with contextlib.suppress(AttributeError):
  1509. delattr(instance, self._cache_attr)
  1510. def _determine_var_type(self) -> Type:
  1511. """Get the type of the var.
  1512. Returns:
  1513. The type of the var.
  1514. """
  1515. hints = get_type_hints(self._fget)
  1516. if "return" in hints:
  1517. return hints["return"]
  1518. return Any
  1519. @property
  1520. def __class__(self) -> Type:
  1521. """Get the class of the var.
  1522. Returns:
  1523. The class of the var.
  1524. """
  1525. return FakeComputedVarBaseClass
  1526. @property
  1527. def fget(self) -> Callable[[BaseState], RETURN_TYPE]:
  1528. """Get the getter function.
  1529. Returns:
  1530. The getter function.
  1531. """
  1532. return self._fget
  1533. class DynamicRouteVar(ComputedVar[Union[str, List[str]]]):
  1534. """A ComputedVar that represents a dynamic route."""
  1535. pass
  1536. if TYPE_CHECKING:
  1537. BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
  1538. @overload
  1539. def computed_var(
  1540. fget: None = None,
  1541. initial_value: Any | types.Unset = types.Unset(),
  1542. cache: bool = False,
  1543. deps: Optional[List[Union[str, Var]]] = None,
  1544. auto_deps: bool = True,
  1545. interval: Optional[Union[datetime.timedelta, int]] = None,
  1546. backend: bool | None = None,
  1547. **kwargs,
  1548. ) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ...
  1549. @overload
  1550. def computed_var(
  1551. fget: Callable[[BASE_STATE], RETURN_TYPE],
  1552. initial_value: RETURN_TYPE | types.Unset = types.Unset(),
  1553. cache: bool = False,
  1554. deps: Optional[List[Union[str, Var]]] = None,
  1555. auto_deps: bool = True,
  1556. interval: Optional[Union[datetime.timedelta, int]] = None,
  1557. backend: bool | None = None,
  1558. **kwargs,
  1559. ) -> ComputedVar[RETURN_TYPE]: ...
  1560. def computed_var(
  1561. fget: Callable[[BASE_STATE], Any] | None = None,
  1562. initial_value: Any | types.Unset = types.Unset(),
  1563. cache: bool = False,
  1564. deps: Optional[List[Union[str, Var]]] = None,
  1565. auto_deps: bool = True,
  1566. interval: Optional[Union[datetime.timedelta, int]] = None,
  1567. backend: bool | None = None,
  1568. **kwargs,
  1569. ) -> ComputedVar | Callable[[Callable[[BASE_STATE], Any]], ComputedVar]:
  1570. """A ComputedVar decorator with or without kwargs.
  1571. Args:
  1572. fget: The getter function.
  1573. initial_value: The initial value of the computed var.
  1574. cache: Whether to cache the computed value.
  1575. deps: Explicit var dependencies to track.
  1576. auto_deps: Whether var dependencies should be auto-determined.
  1577. interval: Interval at which the computed var should be updated.
  1578. backend: Whether the computed var is a backend var.
  1579. **kwargs: additional attributes to set on the instance
  1580. Returns:
  1581. A ComputedVar instance.
  1582. Raises:
  1583. ValueError: If caching is disabled and an update interval is set.
  1584. VarDependencyError: If user supplies dependencies without caching.
  1585. """
  1586. if cache is False and interval is not None:
  1587. raise ValueError("Cannot set update interval without caching.")
  1588. if cache is False and (deps is not None or auto_deps is False):
  1589. raise VarDependencyError("Cannot track dependencies without caching.")
  1590. if fget is not None:
  1591. return ComputedVar(fget, cache=cache)
  1592. def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar:
  1593. return ComputedVar(
  1594. fget,
  1595. initial_value=initial_value,
  1596. cache=cache,
  1597. deps=deps,
  1598. auto_deps=auto_deps,
  1599. interval=interval,
  1600. backend=backend,
  1601. **kwargs,
  1602. )
  1603. return wrapper
  1604. RETURN = TypeVar("RETURN")
  1605. class CustomVarOperationReturn(Var[RETURN]):
  1606. """Base class for custom var operations."""
  1607. @classmethod
  1608. def create(
  1609. cls,
  1610. js_expression: str,
  1611. _var_type: Type[RETURN] | None = None,
  1612. _var_data: VarData | None = None,
  1613. ) -> CustomVarOperationReturn[RETURN]:
  1614. """Create a CustomVarOperation.
  1615. Args:
  1616. js_expression: The JavaScript expression to evaluate.
  1617. _var_type: The type of the var.
  1618. _var_data: Additional hooks and imports associated with the Var.
  1619. Returns:
  1620. The CustomVarOperation.
  1621. """
  1622. return CustomVarOperationReturn(
  1623. _js_expr=js_expression,
  1624. _var_type=_var_type or Any,
  1625. _var_data=_var_data,
  1626. )
  1627. def var_operation_return(
  1628. js_expression: str,
  1629. var_type: Type[RETURN] | None = None,
  1630. var_data: VarData | None = None,
  1631. ) -> CustomVarOperationReturn[RETURN]:
  1632. """Shortcut for creating a CustomVarOperationReturn.
  1633. Args:
  1634. js_expression: The JavaScript expression to evaluate.
  1635. var_type: The type of the var.
  1636. var_data: Additional hooks and imports associated with the Var.
  1637. Returns:
  1638. The CustomVarOperationReturn.
  1639. """
  1640. return CustomVarOperationReturn.create(
  1641. js_expression,
  1642. var_type,
  1643. var_data,
  1644. )
  1645. @dataclasses.dataclass(
  1646. eq=False,
  1647. frozen=True,
  1648. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1649. )
  1650. class CustomVarOperation(CachedVarOperation, Var[T]):
  1651. """Base class for custom var operations."""
  1652. _args: Tuple[Tuple[str, Var], ...] = dataclasses.field(default_factory=tuple)
  1653. _return: CustomVarOperationReturn[T] = dataclasses.field(
  1654. default_factory=lambda: CustomVarOperationReturn.create("")
  1655. )
  1656. @cached_property_no_lock
  1657. def _cached_var_name(self) -> str:
  1658. """Get the cached var name.
  1659. Returns:
  1660. The cached var name.
  1661. """
  1662. return str(self._return)
  1663. @cached_property_no_lock
  1664. def _cached_get_all_var_data(self) -> VarData | None:
  1665. """Get the cached VarData.
  1666. Returns:
  1667. The cached VarData.
  1668. """
  1669. return VarData.merge(
  1670. *map(
  1671. lambda arg: arg[1]._get_all_var_data(),
  1672. self._args,
  1673. ),
  1674. self._return._get_all_var_data(),
  1675. self._var_data,
  1676. )
  1677. @classmethod
  1678. def create(
  1679. cls,
  1680. args: Tuple[Tuple[str, Var], ...],
  1681. return_var: CustomVarOperationReturn[T],
  1682. _var_data: VarData | None = None,
  1683. ) -> CustomVarOperation[T]:
  1684. """Create a CustomVarOperation.
  1685. Args:
  1686. args: The arguments to the operation.
  1687. return_var: The return var.
  1688. _var_data: Additional hooks and imports associated with the Var.
  1689. Returns:
  1690. The CustomVarOperation.
  1691. """
  1692. return CustomVarOperation(
  1693. _js_expr="",
  1694. _var_type=return_var._var_type,
  1695. _var_data=_var_data,
  1696. _args=args,
  1697. _return=return_var,
  1698. )
  1699. class NoneVar(Var[None]):
  1700. """A var representing None."""
  1701. class LiteralNoneVar(LiteralVar, NoneVar):
  1702. """A var representing None."""
  1703. def json(self) -> str:
  1704. """Serialize the var to a JSON string.
  1705. Returns:
  1706. The JSON string.
  1707. """
  1708. return "null"
  1709. @classmethod
  1710. def create(
  1711. cls,
  1712. _var_data: VarData | None = None,
  1713. ) -> LiteralNoneVar:
  1714. """Create a var from a value.
  1715. Args:
  1716. _var_data: Additional hooks and imports associated with the Var.
  1717. Returns:
  1718. The var.
  1719. """
  1720. return LiteralNoneVar(
  1721. _js_expr="null",
  1722. _var_type=None,
  1723. _var_data=_var_data,
  1724. )
  1725. @dataclasses.dataclass(
  1726. eq=False,
  1727. frozen=True,
  1728. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1729. )
  1730. class ToNoneOperation(CachedVarOperation, NoneVar):
  1731. """A var operation that converts a var to None."""
  1732. _original_var: Var = dataclasses.field(
  1733. default_factory=lambda: LiteralNoneVar.create()
  1734. )
  1735. @cached_property_no_lock
  1736. def _cached_var_name(self) -> str:
  1737. """Get the cached var name.
  1738. Returns:
  1739. The cached var name.
  1740. """
  1741. return str(self._original_var)
  1742. @classmethod
  1743. def create(
  1744. cls,
  1745. var: Var,
  1746. _var_data: VarData | None = None,
  1747. ) -> ToNoneOperation:
  1748. """Create a ToNoneOperation.
  1749. Args:
  1750. var: The var to convert to None.
  1751. _var_data: Additional hooks and imports associated with the Var.
  1752. Returns:
  1753. The ToNoneOperation.
  1754. """
  1755. return ToNoneOperation(
  1756. _js_expr="",
  1757. _var_type=None,
  1758. _var_data=_var_data,
  1759. _original_var=var,
  1760. )
  1761. @dataclasses.dataclass(
  1762. eq=False,
  1763. frozen=True,
  1764. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1765. )
  1766. class StateOperation(CachedVarOperation, Var):
  1767. """A var operation that accesses a field on an object."""
  1768. _state_name: str = dataclasses.field(default="")
  1769. _field: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  1770. @cached_property_no_lock
  1771. def _cached_var_name(self) -> str:
  1772. """Get the cached var name.
  1773. Returns:
  1774. The cached var name.
  1775. """
  1776. return f"{str(self._state_name)}.{str(self._field)}"
  1777. def __getattr__(self, name: str) -> Any:
  1778. """Get an attribute of the var.
  1779. Args:
  1780. name: The name of the attribute.
  1781. Returns:
  1782. The attribute.
  1783. """
  1784. if name == "_js_expr":
  1785. return self._cached_var_name
  1786. return getattr(self._field, name)
  1787. @classmethod
  1788. def create(
  1789. cls,
  1790. state_name: str,
  1791. field: Var,
  1792. _var_data: VarData | None = None,
  1793. ) -> StateOperation:
  1794. """Create a DotOperation.
  1795. Args:
  1796. state_name: The name of the state.
  1797. field: The field of the state.
  1798. _var_data: Additional hooks and imports associated with the Var.
  1799. Returns:
  1800. The DotOperation.
  1801. """
  1802. return StateOperation(
  1803. _js_expr="",
  1804. _var_type=field._var_type,
  1805. _var_data=_var_data,
  1806. _state_name=state_name,
  1807. _field=field,
  1808. )
  1809. class ToOperation:
  1810. """A var operation that converts a var to another type."""
  1811. def __getattr__(self, name: str) -> Any:
  1812. """Get an attribute of the var.
  1813. Args:
  1814. name: The name of the attribute.
  1815. Returns:
  1816. The attribute of the var.
  1817. """
  1818. return getattr(object.__getattribute__(self, "_original"), name)
  1819. def __post_init__(self):
  1820. """Post initialization."""
  1821. object.__delattr__(self, "_js_expr")
  1822. def __hash__(self) -> int:
  1823. """Calculate the hash value of the object.
  1824. Returns:
  1825. int: The hash value of the object.
  1826. """
  1827. return hash(object.__getattribute__(self, "_original"))
  1828. def _get_all_var_data(self) -> VarData | None:
  1829. """Get all the var data.
  1830. Returns:
  1831. The var data.
  1832. """
  1833. return VarData.merge(
  1834. object.__getattribute__(self, "_original")._get_all_var_data(),
  1835. self._var_data, # type: ignore
  1836. )
  1837. @classmethod
  1838. def create(
  1839. cls,
  1840. value: Var,
  1841. _var_type: GenericType | None = None,
  1842. _var_data: VarData | None = None,
  1843. ):
  1844. """Create a ToOperation.
  1845. Args:
  1846. value: The value of the var.
  1847. _var_type: The type of the Var.
  1848. _var_data: Additional hooks and imports associated with the Var.
  1849. Returns:
  1850. The ToOperation.
  1851. """
  1852. return cls(
  1853. _js_expr="", # type: ignore
  1854. _var_data=_var_data, # type: ignore
  1855. _var_type=_var_type or cls._default_var_type, # type: ignore
  1856. _original=value, # type: ignore
  1857. )
  1858. def get_uuid_string_var() -> Var:
  1859. """Return a Var that generates a single memoized UUID via .web/utils/state.js.
  1860. useMemo with an empty dependency array ensures that the generated UUID is
  1861. consistent across re-renders of the component.
  1862. Returns:
  1863. A Var that generates a UUID at runtime.
  1864. """
  1865. from reflex.utils.imports import ImportVar
  1866. from reflex.vars import Var
  1867. unique_uuid_var = get_unique_variable_name()
  1868. unique_uuid_var_data = VarData(
  1869. imports={
  1870. f"/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore
  1871. "react": "useMemo",
  1872. },
  1873. hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
  1874. )
  1875. return Var(
  1876. _js_expr=unique_uuid_var,
  1877. _var_type=str,
  1878. _var_data=unique_uuid_var_data,
  1879. )
  1880. # Set of unique variable names.
  1881. USED_VARIABLES = set()
  1882. def get_unique_variable_name() -> str:
  1883. """Get a unique variable name.
  1884. Returns:
  1885. The unique variable name.
  1886. """
  1887. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  1888. if name not in USED_VARIABLES:
  1889. USED_VARIABLES.add(name)
  1890. return name
  1891. return get_unique_variable_name()
  1892. @dataclasses.dataclass(
  1893. eq=True,
  1894. frozen=True,
  1895. )
  1896. class VarData:
  1897. """Metadata associated with a x."""
  1898. # The name of the enclosing state.
  1899. state: str = dataclasses.field(default="")
  1900. # The name of the field in the state.
  1901. field_name: str = dataclasses.field(default="")
  1902. # Imports needed to render this var
  1903. imports: ImmutableParsedImportDict = dataclasses.field(default_factory=tuple)
  1904. # Hooks that need to be present in the component to render this var
  1905. hooks: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
  1906. def __init__(
  1907. self,
  1908. state: str = "",
  1909. field_name: str = "",
  1910. imports: ImportDict | ParsedImportDict | None = None,
  1911. hooks: dict[str, None] | None = None,
  1912. ):
  1913. """Initialize the var data.
  1914. Args:
  1915. state: The name of the enclosing state.
  1916. field_name: The name of the field in the state.
  1917. imports: Imports needed to render this var.
  1918. hooks: Hooks that need to be present in the component to render this var.
  1919. """
  1920. immutable_imports: ImmutableParsedImportDict = tuple(
  1921. sorted(
  1922. ((k, tuple(sorted(v))) for k, v in parse_imports(imports or {}).items())
  1923. )
  1924. )
  1925. object.__setattr__(self, "state", state)
  1926. object.__setattr__(self, "field_name", field_name)
  1927. object.__setattr__(self, "imports", immutable_imports)
  1928. object.__setattr__(self, "hooks", tuple(hooks or {}))
  1929. def old_school_imports(self) -> ImportDict:
  1930. """Return the imports as a mutable dict.
  1931. Returns:
  1932. The imports as a mutable dict.
  1933. """
  1934. return dict((k, list(v)) for k, v in self.imports)
  1935. @classmethod
  1936. def merge(cls, *others: VarData | None) -> VarData | None:
  1937. """Merge multiple var data objects.
  1938. Args:
  1939. *others: The var data objects to merge.
  1940. Returns:
  1941. The merged var data object.
  1942. """
  1943. state = ""
  1944. field_name = ""
  1945. _imports = {}
  1946. hooks = {}
  1947. for var_data in others:
  1948. if var_data is None:
  1949. continue
  1950. state = state or var_data.state
  1951. field_name = field_name or var_data.field_name
  1952. _imports = imports.merge_imports(_imports, var_data.imports)
  1953. hooks.update(
  1954. var_data.hooks
  1955. if isinstance(var_data.hooks, dict)
  1956. else {k: None for k in var_data.hooks}
  1957. )
  1958. if state or _imports or hooks or field_name:
  1959. return VarData(
  1960. state=state,
  1961. field_name=field_name,
  1962. imports=_imports,
  1963. hooks=hooks,
  1964. )
  1965. return None
  1966. def __bool__(self) -> bool:
  1967. """Check if the var data is non-empty.
  1968. Returns:
  1969. True if any field is set to a non-default value.
  1970. """
  1971. return bool(self.state or self.imports or self.hooks or self.field_name)
  1972. @classmethod
  1973. def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarData:
  1974. """Set the state of the var.
  1975. Args:
  1976. state: The state to set or the full name of the state.
  1977. field_name: The name of the field in the state. Optional.
  1978. Returns:
  1979. The var with the set state.
  1980. """
  1981. from reflex.utils import format
  1982. state_name = state if isinstance(state, str) else state.get_full_name()
  1983. return VarData(
  1984. state=state_name,
  1985. field_name=field_name,
  1986. hooks={
  1987. "const {0} = useContext(StateContexts.{0})".format(
  1988. format.format_state_name(state_name)
  1989. ): None
  1990. },
  1991. imports={
  1992. f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  1993. "react": [ImportVar(tag="useContext")],
  1994. },
  1995. )
  1996. def _decode_var_immutable(value: str) -> tuple[VarData | None, str]:
  1997. """Decode the state name from a formatted var.
  1998. Args:
  1999. value: The value to extract the state name from.
  2000. Returns:
  2001. The extracted state name and the value without the state name.
  2002. """
  2003. var_datas = []
  2004. if isinstance(value, str):
  2005. # fast path if there is no encoded VarData
  2006. if constants.REFLEX_VAR_OPENING_TAG not in value:
  2007. return None, value
  2008. offset = 0
  2009. # Find all tags.
  2010. while m := _decode_var_pattern.search(value):
  2011. start, end = m.span()
  2012. value = value[:start] + value[end:]
  2013. serialized_data = m.group(1)
  2014. if serialized_data.isnumeric() or (
  2015. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  2016. ):
  2017. # This is a global immutable var.
  2018. var = _global_vars[int(serialized_data)]
  2019. var_data = var._get_all_var_data()
  2020. if var_data is not None:
  2021. var_datas.append(var_data)
  2022. offset += end - start
  2023. return VarData.merge(*var_datas) if var_datas else None, value
  2024. # Compile regex for finding reflex var tags.
  2025. _decode_var_pattern_re = (
  2026. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  2027. )
  2028. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  2029. # Defined global immutable vars.
  2030. _global_vars: Dict[int, Var] = {}
  2031. def _extract_var_data(value: Iterable) -> list[VarData | None]:
  2032. """Extract the var imports and hooks from an iterable containing a Var.
  2033. Args:
  2034. value: The iterable to extract the VarData from
  2035. Returns:
  2036. The extracted VarDatas.
  2037. """
  2038. from reflex.style import Style
  2039. from reflex.vars import Var
  2040. var_datas = []
  2041. with contextlib.suppress(TypeError):
  2042. for sub in value:
  2043. if isinstance(sub, Var):
  2044. var_datas.append(sub._var_data)
  2045. elif not isinstance(sub, str):
  2046. # Recurse into dict values.
  2047. if hasattr(sub, "values") and callable(sub.values):
  2048. var_datas.extend(_extract_var_data(sub.values()))
  2049. # Recurse into iterable values (or dict keys).
  2050. var_datas.extend(_extract_var_data(sub))
  2051. # Style objects should already have _var_data.
  2052. if isinstance(value, Style):
  2053. var_datas.append(value._var_data)
  2054. else:
  2055. # Recurse when value is a dict itself.
  2056. values = getattr(value, "values", None)
  2057. if callable(values):
  2058. var_datas.extend(_extract_var_data(values()))
  2059. return var_datas
  2060. # These names were changed in reflex 0.3.0
  2061. REPLACED_NAMES = {
  2062. "full_name": "_var_full_name",
  2063. "name": "_js_expr",
  2064. "state": "_var_data.state",
  2065. "type_": "_var_type",
  2066. "is_local": "_var_is_local",
  2067. "is_string": "_var_is_string",
  2068. "set_state": "_var_set_state",
  2069. "deps": "_deps",
  2070. }
  2071. dispatchers: Dict[GenericType, Callable[[Var], Var]] = {}
  2072. def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]:
  2073. """Register a function to transform a Var.
  2074. Args:
  2075. fn: The function to register.
  2076. Returns:
  2077. The decorator.
  2078. Raises:
  2079. TypeError: If the return type of the function is not a Var.
  2080. TypeError: If the Var return type does not have a generic type.
  2081. ValueError: If a function for the generic type is already registered.
  2082. """
  2083. return_type = fn.__annotations__["return"]
  2084. origin = get_origin(return_type)
  2085. if origin is not Var:
  2086. raise TypeError(
  2087. f"Expected return type of {fn.__name__} to be a Var, got {origin}."
  2088. )
  2089. generic_args = get_args(return_type)
  2090. if not generic_args:
  2091. raise TypeError(
  2092. f"Expected Var return type of {fn.__name__} to have a generic type."
  2093. )
  2094. generic_type = get_origin(generic_args[0]) or generic_args[0]
  2095. if generic_type in dispatchers:
  2096. raise ValueError(f"Function for {generic_type} already registered.")
  2097. dispatchers[generic_type] = fn
  2098. return fn
  2099. def generic_type_to_actual_type_map(
  2100. generic_type: GenericType, actual_type: GenericType
  2101. ) -> Dict[TypeVar, GenericType]:
  2102. """Map the generic type to the actual type.
  2103. Args:
  2104. generic_type: The generic type.
  2105. actual_type: The actual type.
  2106. Returns:
  2107. The mapping of type variables to actual types.
  2108. Raises:
  2109. TypeError: If the generic type and actual type do not match.
  2110. TypeError: If the number of generic arguments and actual arguments do not match.
  2111. """
  2112. generic_origin = get_origin(generic_type) or generic_type
  2113. actual_origin = get_origin(actual_type) or actual_type
  2114. if generic_origin is not actual_origin:
  2115. if isinstance(generic_origin, TypeVar):
  2116. return {generic_origin: actual_origin}
  2117. raise TypeError(
  2118. f"Type mismatch: expected {generic_origin}, got {actual_origin}."
  2119. )
  2120. generic_args = get_args(generic_type)
  2121. actual_args = get_args(actual_type)
  2122. if len(generic_args) != len(actual_args):
  2123. raise TypeError(
  2124. f"Number of generic arguments mismatch: expected {len(generic_args)}, got {len(actual_args)}."
  2125. )
  2126. # call recursively for nested generic types and merge the results
  2127. return {
  2128. k: v
  2129. for generic_arg, actual_arg in zip(generic_args, actual_args)
  2130. for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items()
  2131. }
  2132. def resolve_generic_type_with_mapping(
  2133. generic_type: GenericType, type_mapping: Dict[TypeVar, GenericType]
  2134. ):
  2135. """Resolve a generic type with a type mapping.
  2136. Args:
  2137. generic_type: The generic type.
  2138. type_mapping: The type mapping.
  2139. Returns:
  2140. The resolved generic type.
  2141. """
  2142. if isinstance(generic_type, TypeVar):
  2143. return type_mapping.get(generic_type, generic_type)
  2144. generic_origin = get_origin(generic_type) or generic_type
  2145. generic_args = get_args(generic_type)
  2146. if not generic_args:
  2147. return generic_type
  2148. mapping_for_older_python = {
  2149. list: List,
  2150. set: Set,
  2151. dict: Dict,
  2152. tuple: Tuple,
  2153. frozenset: FrozenSet,
  2154. }
  2155. return mapping_for_older_python.get(generic_origin, generic_origin)[
  2156. tuple(
  2157. resolve_generic_type_with_mapping(arg, type_mapping) for arg in generic_args
  2158. )
  2159. ]
  2160. def resolve_arg_type_from_return_type(
  2161. arg_type: GenericType, return_type: GenericType, actual_return_type: GenericType
  2162. ) -> GenericType:
  2163. """Resolve the argument type from the return type.
  2164. Args:
  2165. arg_type: The argument type.
  2166. return_type: The return type.
  2167. actual_return_type: The requested return type.
  2168. Returns:
  2169. The argument type without the generics that are resolved.
  2170. """
  2171. return resolve_generic_type_with_mapping(
  2172. arg_type, generic_type_to_actual_type_map(return_type, actual_return_type)
  2173. )
  2174. def dispatch(
  2175. field_name: str,
  2176. var_data: VarData,
  2177. result_var_type: GenericType,
  2178. existing_var: Var | None = None,
  2179. ) -> Var:
  2180. """Dispatch a Var to the appropriate transformation function.
  2181. Args:
  2182. field_name: The name of the field.
  2183. var_data: The VarData associated with the Var.
  2184. result_var_type: The type of the Var.
  2185. existing_var: The existing Var to transform. Optional.
  2186. Returns:
  2187. The transformed Var.
  2188. Raises:
  2189. TypeError: If the return type of the function is not a Var.
  2190. TypeError: If the Var return type does not have a generic type.
  2191. TypeError: If the first argument of the function is not a Var.
  2192. TypeError: If the first argument of the function does not have a generic type
  2193. """
  2194. result_origin_var_type = get_origin(result_var_type) or result_var_type
  2195. if result_origin_var_type in dispatchers:
  2196. fn = dispatchers[result_origin_var_type]
  2197. fn_first_arg_type = list(inspect.signature(fn).parameters.values())[
  2198. 0
  2199. ].annotation
  2200. fn_return = inspect.signature(fn).return_annotation
  2201. fn_return_origin = get_origin(fn_return) or fn_return
  2202. if fn_return_origin is not Var:
  2203. raise TypeError(
  2204. f"Expected return type of {fn.__name__} to be a Var, got {fn_return}."
  2205. )
  2206. fn_return_generic_args = get_args(fn_return)
  2207. if not fn_return_generic_args:
  2208. raise TypeError(f"Expected generic type of {fn_return} to be a type.")
  2209. arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type
  2210. if arg_origin is not Var:
  2211. raise TypeError(
  2212. f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}."
  2213. )
  2214. arg_generic_args = get_args(fn_first_arg_type)
  2215. if not arg_generic_args:
  2216. raise TypeError(
  2217. f"Expected generic type of {fn_first_arg_type} to be a type."
  2218. )
  2219. arg_type = arg_generic_args[0]
  2220. fn_return_type = fn_return_generic_args[0]
  2221. var = (
  2222. Var(
  2223. field_name,
  2224. _var_data=var_data,
  2225. _var_type=resolve_arg_type_from_return_type(
  2226. arg_type, fn_return_type, result_var_type
  2227. ),
  2228. ).guess_type()
  2229. if existing_var is None
  2230. else existing_var._replace(
  2231. _var_type=resolve_arg_type_from_return_type(
  2232. arg_type, fn_return_type, result_var_type
  2233. ),
  2234. _var_data=var_data,
  2235. _js_expr=field_name,
  2236. ).guess_type()
  2237. )
  2238. return fn(var)
  2239. if existing_var is not None:
  2240. return existing_var._replace(
  2241. _js_expr=field_name,
  2242. _var_data=var_data,
  2243. _var_type=result_var_type,
  2244. ).guess_type()
  2245. return Var(
  2246. field_name,
  2247. _var_data=var_data,
  2248. _var_type=result_var_type,
  2249. ).guess_type()