vars.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. """Define a state var."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import dis
  6. import inspect
  7. import json
  8. import random
  9. import re
  10. import string
  11. import sys
  12. from types import CodeType, FunctionType
  13. from typing import (
  14. TYPE_CHECKING,
  15. Any,
  16. Callable,
  17. Dict,
  18. Iterable,
  19. List,
  20. Literal,
  21. Optional,
  22. Set,
  23. Tuple,
  24. Type,
  25. Union,
  26. _GenericAlias, # type: ignore
  27. cast,
  28. get_args,
  29. get_origin,
  30. get_type_hints,
  31. )
  32. import pydantic
  33. from reflex import constants
  34. from reflex.base import Base
  35. from reflex.utils import console, format, imports, serializers, types
  36. # This module used to export ImportVar itself, so we still import it for export here
  37. from reflex.utils.imports import ImportDict, ImportVar
  38. if TYPE_CHECKING:
  39. from reflex.state import BaseState
  40. # Set of unique variable names.
  41. USED_VARIABLES = set()
  42. # Supported operators for all types.
  43. ALL_OPS = ["==", "!=", "!==", "===", "&&", "||"]
  44. # Delimiters used between function args or operands.
  45. DELIMITERS = [","]
  46. # Mapping of valid operations for different type combinations.
  47. OPERATION_MAPPING = {
  48. (int, int): {
  49. "+",
  50. "-",
  51. "/",
  52. "//",
  53. "*",
  54. "%",
  55. "**",
  56. ">",
  57. "<",
  58. "<=",
  59. ">=",
  60. "|",
  61. "&",
  62. },
  63. (int, str): {"*"},
  64. (int, list): {"*"},
  65. (str, str): {"+", ">", "<", "<=", ">="},
  66. (float, float): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  67. (float, int): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  68. (list, list): {"+", ">", "<", "<=", ">="},
  69. }
  70. # These names were changed in reflex 0.3.0
  71. REPLACED_NAMES = {
  72. "full_name": "_var_full_name",
  73. "name": "_var_name",
  74. "state": "_var_data.state",
  75. "type_": "_var_type",
  76. "is_local": "_var_is_local",
  77. "is_string": "_var_is_string",
  78. "set_state": "_var_set_state",
  79. "deps": "_deps",
  80. }
  81. PYTHON_JS_TYPE_MAP = {
  82. (int, float): "number",
  83. (str,): "string",
  84. (bool,): "boolean",
  85. (list, tuple): "Array",
  86. (dict,): "Object",
  87. (None,): "null",
  88. }
  89. def get_unique_variable_name() -> str:
  90. """Get a unique variable name.
  91. Returns:
  92. The unique variable name.
  93. """
  94. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  95. if name not in USED_VARIABLES:
  96. USED_VARIABLES.add(name)
  97. return name
  98. return get_unique_variable_name()
  99. class VarData(Base):
  100. """Metadata associated with a Var."""
  101. # The name of the enclosing state.
  102. state: str = ""
  103. # Imports needed to render this var
  104. imports: ImportDict = {}
  105. # Hooks that need to be present in the component to render this var
  106. hooks: Set[str] = set()
  107. @classmethod
  108. def merge(cls, *others: VarData | None) -> VarData | None:
  109. """Merge multiple var data objects.
  110. Args:
  111. *others: The var data objects to merge.
  112. Returns:
  113. The merged var data object.
  114. """
  115. state = ""
  116. _imports = {}
  117. hooks = set()
  118. for var_data in others:
  119. if var_data is None:
  120. continue
  121. state = state or var_data.state
  122. _imports = imports.merge_imports(_imports, var_data.imports)
  123. hooks.update(var_data.hooks)
  124. return (
  125. cls(
  126. state=state,
  127. imports=_imports,
  128. hooks=hooks,
  129. )
  130. or None
  131. )
  132. def __bool__(self) -> bool:
  133. """Check if the var data is non-empty.
  134. Returns:
  135. True if any field is set to a non-default value.
  136. """
  137. return bool(self.state or self.imports or self.hooks)
  138. def __eq__(self, other: Any) -> bool:
  139. """Check if two var data objects are equal.
  140. Args:
  141. other: The other var data object to compare.
  142. Returns:
  143. True if all fields are equal and collapsed imports are equal.
  144. """
  145. if not isinstance(other, VarData):
  146. return False
  147. return (
  148. self.state == other.state
  149. and self.hooks == other.hooks
  150. and imports.collapse_imports(self.imports)
  151. == imports.collapse_imports(other.imports)
  152. )
  153. def dict(self) -> dict:
  154. """Convert the var data to a dictionary.
  155. Returns:
  156. The var data dictionary.
  157. """
  158. return {
  159. "state": self.state,
  160. "imports": {
  161. lib: [import_var.dict() for import_var in import_vars]
  162. for lib, import_vars in self.imports.items()
  163. },
  164. "hooks": list(self.hooks),
  165. }
  166. def _encode_var(value: Var) -> str:
  167. """Encode the state name into a formatted var.
  168. Args:
  169. value: The value to encode the state name into.
  170. Returns:
  171. The encoded var.
  172. """
  173. if value._var_data:
  174. return f"<reflex.Var>{value._var_data.json()}</reflex.Var>" + str(value)
  175. return str(value)
  176. def _decode_var(value: str) -> tuple[VarData | None, str]:
  177. """Decode the state name from a formatted var.
  178. Args:
  179. value: The value to extract the state name from.
  180. Returns:
  181. The extracted state name and the value without the state name.
  182. """
  183. var_datas = []
  184. if isinstance(value, str):
  185. # Extract the state name from a formatted var
  186. while m := re.match(
  187. pattern=r"(.*)<reflex.Var>(.*)</reflex.Var>(.*)",
  188. string=value,
  189. flags=re.DOTALL, # Ensure . matches newline characters.
  190. ):
  191. value = m.group(1) + m.group(3)
  192. try:
  193. var_datas.append(VarData.parse_raw(m.group(2)))
  194. except pydantic.ValidationError:
  195. # If the VarData is invalid, it was probably json-encoded twice...
  196. var_datas.append(VarData.parse_raw(json.loads(f'"{m.group(2)}"')))
  197. if var_datas:
  198. return VarData.merge(*var_datas), value
  199. return None, value
  200. def _extract_var_data(value: Iterable) -> list[VarData | None]:
  201. """Extract the var imports and hooks from an iterable containing a Var.
  202. Args:
  203. value: The iterable to extract the VarData from
  204. Returns:
  205. The extracted VarDatas.
  206. """
  207. from reflex.style import Style
  208. var_datas = []
  209. with contextlib.suppress(TypeError):
  210. for sub in value:
  211. if isinstance(sub, Var):
  212. var_datas.append(sub._var_data)
  213. elif not isinstance(sub, str):
  214. # Recurse into dict values.
  215. if hasattr(sub, "values") and callable(sub.values):
  216. var_datas.extend(_extract_var_data(sub.values()))
  217. # Recurse into iterable values (or dict keys).
  218. var_datas.extend(_extract_var_data(sub))
  219. # Style objects should already have _var_data.
  220. if isinstance(value, Style):
  221. var_datas.append(value._var_data)
  222. else:
  223. # Recurse when value is a dict itself.
  224. values = getattr(value, "values", None)
  225. if callable(values):
  226. var_datas.extend(_extract_var_data(values()))
  227. return var_datas
  228. class Var:
  229. """An abstract var."""
  230. # The name of the var.
  231. _var_name: str
  232. # The type of the var.
  233. _var_type: Type
  234. # Whether this is a local javascript variable.
  235. _var_is_local: bool
  236. # Whether the var is a string literal.
  237. _var_is_string: bool
  238. # _var_full_name should be prefixed with _var_state
  239. _var_full_name_needs_state_prefix: bool
  240. # Extra metadata associated with the Var
  241. _var_data: Optional[VarData]
  242. @classmethod
  243. def create(
  244. cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
  245. ) -> Var | None:
  246. """Create a var from a value.
  247. Args:
  248. value: The value to create the var from.
  249. _var_is_local: Whether the var is local.
  250. _var_is_string: Whether the var is a string literal.
  251. Returns:
  252. The var.
  253. Raises:
  254. TypeError: If the value is JSON-unserializable.
  255. """
  256. # Check for none values.
  257. if value is None:
  258. return None
  259. # If the value is already a var, do nothing.
  260. if isinstance(value, Var):
  261. return value
  262. # Try to pull the imports and hooks from contained values.
  263. _var_data = None
  264. if not isinstance(value, str):
  265. _var_data = VarData.merge(*_extract_var_data(value))
  266. # Try to serialize the value.
  267. type_ = type(value)
  268. name = value if type_ in types.JSONType else serializers.serialize(value)
  269. if name is None:
  270. raise TypeError(
  271. f"No JSON serializer found for var {value} of type {type_}."
  272. )
  273. name = name if isinstance(name, str) else format.json_dumps(name)
  274. return BaseVar(
  275. _var_name=name,
  276. _var_type=type_,
  277. _var_is_local=_var_is_local,
  278. _var_is_string=_var_is_string,
  279. _var_data=_var_data,
  280. )
  281. @classmethod
  282. def create_safe(
  283. cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
  284. ) -> Var:
  285. """Create a var from a value, asserting that it is not None.
  286. Args:
  287. value: The value to create the var from.
  288. _var_is_local: Whether the var is local.
  289. _var_is_string: Whether the var is a string literal.
  290. Returns:
  291. The var.
  292. """
  293. var = cls.create(
  294. value,
  295. _var_is_local=_var_is_local,
  296. _var_is_string=_var_is_string,
  297. )
  298. assert var is not None
  299. return var
  300. @classmethod
  301. def __class_getitem__(cls, type_: str) -> _GenericAlias:
  302. """Get a typed var.
  303. Args:
  304. type_: The type of the var.
  305. Returns:
  306. The var class item.
  307. """
  308. return _GenericAlias(cls, type_)
  309. def __post_init__(self) -> None:
  310. """Post-initialize the var."""
  311. # Decode any inline Var markup and apply it to the instance
  312. _var_data, _var_name = _decode_var(self._var_name)
  313. if _var_data:
  314. self._var_name = _var_name
  315. self._var_data = VarData.merge(self._var_data, _var_data)
  316. def _replace(self, merge_var_data=None, **kwargs: Any) -> Var:
  317. """Make a copy of this Var with updated fields.
  318. Args:
  319. merge_var_data: VarData to merge into the existing VarData.
  320. **kwargs: Var fields to update.
  321. Returns:
  322. A new BaseVar with the updated fields overwriting the corresponding fields in this Var.
  323. """
  324. field_values = dict(
  325. _var_name=kwargs.pop("_var_name", self._var_name),
  326. _var_type=kwargs.pop("_var_type", self._var_type),
  327. _var_is_local=kwargs.pop("_var_is_local", self._var_is_local),
  328. _var_is_string=kwargs.pop("_var_is_string", self._var_is_string),
  329. _var_full_name_needs_state_prefix=kwargs.pop(
  330. "_var_full_name_needs_state_prefix",
  331. self._var_full_name_needs_state_prefix,
  332. ),
  333. _var_data=VarData.merge(
  334. kwargs.get("_var_data", self._var_data), merge_var_data
  335. ),
  336. )
  337. return BaseVar(**field_values)
  338. def _decode(self) -> Any:
  339. """Decode Var as a python value.
  340. Note that Var with state set cannot be decoded python-side and will be
  341. returned as full_name.
  342. Returns:
  343. The decoded value or the Var name.
  344. """
  345. if self._var_is_string:
  346. return self._var_name
  347. try:
  348. return json.loads(self._var_name)
  349. except ValueError:
  350. return self._var_name
  351. def equals(self, other: Var) -> bool:
  352. """Check if two vars are equal.
  353. Args:
  354. other: The other var to compare.
  355. Returns:
  356. Whether the vars are equal.
  357. """
  358. return (
  359. self._var_name == other._var_name
  360. and self._var_type == other._var_type
  361. and self._var_is_local == other._var_is_local
  362. and self._var_full_name_needs_state_prefix
  363. == other._var_full_name_needs_state_prefix
  364. and self._var_data == other._var_data
  365. )
  366. def _merge(self, other) -> Var:
  367. """Merge two or more dicts.
  368. Args:
  369. other: The other var to merge.
  370. Returns:
  371. The merged var.
  372. """
  373. if other is None:
  374. return self._replace()
  375. if not isinstance(other, Var):
  376. other = Var.create(other)
  377. return self._replace(
  378. _var_name=f"{{...{self._var_name}, ...{other._var_name}}}" # type: ignore
  379. )
  380. def to_string(self, json: bool = True) -> Var:
  381. """Convert a var to a string.
  382. Args:
  383. json: Whether to convert to a JSON string.
  384. Returns:
  385. The stringified var.
  386. """
  387. fn = "JSON.stringify" if json else "String"
  388. return self.operation(fn=fn, type_=str)
  389. def __hash__(self) -> int:
  390. """Define a hash function for a var.
  391. Returns:
  392. The hash of the var.
  393. """
  394. return hash((self._var_name, str(self._var_type)))
  395. def __str__(self) -> str:
  396. """Wrap the var so it can be used in templates.
  397. Returns:
  398. The wrapped var, i.e. {state.var}.
  399. """
  400. out = (
  401. self._var_full_name
  402. if self._var_is_local
  403. else format.wrap(self._var_full_name, "{")
  404. )
  405. if self._var_is_string:
  406. out = format.format_string(out)
  407. return out
  408. def __bool__(self) -> bool:
  409. """Raise exception if using Var in a boolean context.
  410. Raises:
  411. TypeError: when attempting to bool-ify the Var.
  412. """
  413. raise TypeError(
  414. f"Cannot convert Var {self._var_full_name!r} to bool for use with `if`, `and`, `or`, and `not`. "
  415. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  416. )
  417. def __iter__(self) -> Any:
  418. """Raise exception if using Var in an iterable context.
  419. Raises:
  420. TypeError: when attempting to iterate over the Var.
  421. """
  422. raise TypeError(
  423. f"Cannot iterate over Var {self._var_full_name!r}. Instead use `rx.foreach`."
  424. )
  425. def __format__(self, format_spec: str) -> str:
  426. """Format the var into a Javascript equivalent to an f-string.
  427. Args:
  428. format_spec: The format specifier (Ignored for now).
  429. Returns:
  430. The formatted var.
  431. """
  432. # Encode the _var_data into the formatted output for tracking purposes.
  433. str_self = _encode_var(self)
  434. if self._var_is_local:
  435. return str_self
  436. return f"${str_self}"
  437. def __getitem__(self, i: Any) -> Var:
  438. """Index into a var.
  439. Args:
  440. i: The index to index into.
  441. Returns:
  442. The indexed var.
  443. Raises:
  444. TypeError: If the var is not indexable.
  445. """
  446. # Indexing is only supported for strings, lists, tuples, dicts, and dataframes.
  447. if not (
  448. types._issubclass(self._var_type, Union[List, Dict, Tuple, str])
  449. or types.is_dataframe(self._var_type)
  450. ):
  451. if self._var_type == Any:
  452. raise TypeError(
  453. "Could not index into var of type Any. (If you are trying to index into a state var, "
  454. "add the correct type annotation to the var.)"
  455. )
  456. raise TypeError(
  457. f"Var {self._var_name} of type {self._var_type} does not support indexing."
  458. )
  459. # The type of the indexed var.
  460. type_ = Any
  461. # Convert any vars to local vars.
  462. if isinstance(i, Var):
  463. i = i._replace(_var_is_local=True)
  464. # Handle list/tuple/str indexing.
  465. if types._issubclass(self._var_type, Union[List, Tuple, str]):
  466. # List/Tuple/String indices must be ints, slices, or vars.
  467. if (
  468. not isinstance(i, types.get_args(Union[int, slice, Var]))
  469. or isinstance(i, Var)
  470. and not i._var_type == int
  471. ):
  472. raise TypeError("Index must be an integer or an integer var.")
  473. # Handle slices first.
  474. if isinstance(i, slice):
  475. # Get the start and stop indices.
  476. start = i.start or 0
  477. stop = i.stop or "undefined"
  478. # Use the slice function.
  479. return self._replace(
  480. _var_name=f"{self._var_name}.slice({start}, {stop})",
  481. _var_is_string=False,
  482. )
  483. # Get the type of the indexed var.
  484. if types.is_generic_alias(self._var_type):
  485. type_ = types.get_args(self._var_type)[0]
  486. elif types._issubclass(self._var_type, str):
  487. type_ = str
  488. # Use `at` to support negative indices.
  489. return self._replace(
  490. _var_name=f"{self._var_name}.at({i})",
  491. _var_type=type_,
  492. _var_is_string=False,
  493. )
  494. # Dictionary / dataframe indexing.
  495. # Tuples are currently not supported as indexes.
  496. if (
  497. (
  498. types._issubclass(self._var_type, Dict)
  499. or types.is_dataframe(self._var_type)
  500. )
  501. and not isinstance(i, types.get_args(Union[int, str, float, Var]))
  502. ) or (
  503. isinstance(i, Var)
  504. and not types._issubclass(
  505. i._var_type, types.get_args(Union[int, str, float])
  506. )
  507. ):
  508. raise TypeError(
  509. "Index must be one of the following types: int, str, int or str Var"
  510. )
  511. # Get the type of the indexed var.
  512. if isinstance(i, str):
  513. i = format.wrap(i, '"')
  514. type_ = (
  515. types.get_args(self._var_type)[1]
  516. if types.is_generic_alias(self._var_type)
  517. else Any
  518. )
  519. # Use normal indexing here.
  520. return self._replace(
  521. _var_name=f"{self._var_name}[{i}]",
  522. _var_type=type_,
  523. _var_is_string=False,
  524. )
  525. def __getattr__(self, name: str) -> Var:
  526. """Get a var attribute.
  527. Args:
  528. name: The name of the attribute.
  529. Returns:
  530. The var attribute.
  531. Raises:
  532. AttributeError: If the var is wrongly annotated or can't find attribute.
  533. TypeError: If an annotation to the var isn't provided.
  534. """
  535. # Check if the attribute is one of the class fields.
  536. if not name.startswith("_"):
  537. if self._var_type == Any:
  538. raise TypeError(
  539. f"You must provide an annotation for the state var `{self._var_full_name}`. Annotation cannot be `{self._var_type}`"
  540. ) from None
  541. is_optional = types.is_optional(self._var_type)
  542. type_ = types.get_attribute_access_type(self._var_type, name)
  543. if type_ is not None:
  544. return self._replace(
  545. _var_name=f"{self._var_name}{'?' if is_optional else ''}.{name}",
  546. _var_type=type_,
  547. _var_is_string=False,
  548. )
  549. if name in REPLACED_NAMES:
  550. raise AttributeError(
  551. f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
  552. )
  553. raise AttributeError(
  554. f"The State var `{self._var_full_name}` has no attribute '{name}' or may have been annotated "
  555. f"wrongly."
  556. )
  557. raise AttributeError(
  558. f"The State var has no attribute '{name}' or may have been annotated wrongly.",
  559. )
  560. def operation(
  561. self,
  562. op: str = "",
  563. other: Var | None = None,
  564. type_: Type | None = None,
  565. flip: bool = False,
  566. fn: str | None = None,
  567. invoke_fn: bool = False,
  568. ) -> Var:
  569. """Perform an operation on a var.
  570. Args:
  571. op: The operation to perform.
  572. other: The other var to perform the operation on.
  573. type_: The type of the operation result.
  574. flip: Whether to flip the order of the operation.
  575. fn: A function to apply to the operation.
  576. invoke_fn: Whether to invoke the function.
  577. Returns:
  578. The operation result.
  579. Raises:
  580. TypeError: If the operation between two operands is invalid.
  581. ValueError: If flip is set to true and value of operand is not provided
  582. """
  583. if isinstance(other, str):
  584. other = Var.create(json.dumps(other))
  585. else:
  586. other = Var.create(other)
  587. type_ = type_ or self._var_type
  588. if other is None and flip:
  589. raise ValueError(
  590. "flip_operands cannot be set to True if the value of 'other' operand is not provided"
  591. )
  592. left_operand, right_operand = (other, self) if flip else (self, other)
  593. def get_operand_full_name(operand):
  594. # operand vars that are string literals need to be wrapped in back ticks.
  595. return (
  596. operand._var_name_unwrapped
  597. if operand._var_is_string
  598. and not operand._var_state
  599. and operand._var_is_local
  600. else operand._var_full_name
  601. )
  602. if other is not None:
  603. # check if the operation between operands is valid.
  604. if op and not self.is_valid_operation(
  605. types.get_base_class(left_operand._var_type), # type: ignore
  606. types.get_base_class(right_operand._var_type), # type: ignore
  607. op,
  608. ):
  609. raise TypeError(
  610. f"Unsupported Operand type(s) for {op}: `{left_operand._var_full_name}` of type {left_operand._var_type.__name__} and `{right_operand._var_full_name}` of type {right_operand._var_type.__name__}" # type: ignore
  611. )
  612. left_operand_full_name = get_operand_full_name(left_operand)
  613. right_operand_full_name = get_operand_full_name(right_operand)
  614. # apply function to operands
  615. if fn is not None:
  616. if invoke_fn:
  617. # invoke the function on left operand.
  618. operation_name = f"{left_operand_full_name}.{fn}({right_operand_full_name})" # type: ignore
  619. else:
  620. # pass the operands as arguments to the function.
  621. operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
  622. operation_name = f"{fn}({operation_name})"
  623. else:
  624. # apply operator to operands (left operand <operator> right_operand)
  625. operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
  626. operation_name = format.wrap(operation_name, "(")
  627. else:
  628. # apply operator to left operand (<operator> left_operand)
  629. operation_name = f"{op}{get_operand_full_name(self)}"
  630. # apply function to operands
  631. if fn is not None:
  632. operation_name = (
  633. f"{fn}({operation_name})"
  634. if not invoke_fn
  635. else f"{get_operand_full_name(self)}.{fn}()"
  636. )
  637. return self._replace(
  638. _var_name=operation_name,
  639. _var_type=type_,
  640. _var_is_string=False,
  641. _var_full_name_needs_state_prefix=False,
  642. merge_var_data=other._var_data if other is not None else None,
  643. )
  644. @staticmethod
  645. def is_valid_operation(
  646. operand1_type: Type, operand2_type: Type, operator: str
  647. ) -> bool:
  648. """Check if an operation between two operands is valid.
  649. Args:
  650. operand1_type: Type of the operand
  651. operand2_type: Type of the second operand
  652. operator: The operator.
  653. Returns:
  654. Whether operation is valid or not
  655. """
  656. if operator in ALL_OPS or operator in DELIMITERS:
  657. return True
  658. # bools are subclasses of ints
  659. pair = tuple(
  660. sorted(
  661. [
  662. int if operand1_type == bool else operand1_type,
  663. int if operand2_type == bool else operand2_type,
  664. ],
  665. key=lambda x: x.__name__,
  666. )
  667. )
  668. return pair in OPERATION_MAPPING and operator in OPERATION_MAPPING[pair]
  669. def compare(self, op: str, other: Var) -> Var:
  670. """Compare two vars with inequalities.
  671. Args:
  672. op: The comparison operator.
  673. other: The other var to compare with.
  674. Returns:
  675. The comparison result.
  676. """
  677. return self.operation(op, other, bool)
  678. def __invert__(self) -> Var:
  679. """Invert a var.
  680. Returns:
  681. The inverted var.
  682. """
  683. return self.operation("!", type_=bool)
  684. def __neg__(self) -> Var:
  685. """Negate a var.
  686. Returns:
  687. The negated var.
  688. """
  689. return self.operation(fn="-")
  690. def __abs__(self) -> Var:
  691. """Get the absolute value of a var.
  692. Returns:
  693. A var with the absolute value.
  694. """
  695. return self.operation(fn="Math.abs")
  696. def length(self) -> Var:
  697. """Get the length of a list var.
  698. Returns:
  699. A var with the absolute value.
  700. Raises:
  701. TypeError: If the var is not a list.
  702. """
  703. if not types._issubclass(self._var_type, List):
  704. raise TypeError(f"Cannot get length of non-list var {self}.")
  705. return self._replace(
  706. _var_name=f"{self._var_name}.length",
  707. _var_type=int,
  708. _var_is_string=False,
  709. )
  710. def _type(self) -> Var:
  711. """Get the type of the Var in Javascript.
  712. Returns:
  713. A var representing the type check.
  714. """
  715. return self._replace(
  716. _var_name=f"typeof {self._var_full_name}",
  717. _var_type=str,
  718. _var_is_string=False,
  719. _var_full_name_needs_state_prefix=False,
  720. )
  721. def __eq__(self, other: Union[Var, Type]) -> Var:
  722. """Perform an equality comparison.
  723. Args:
  724. other: The other var to compare with.
  725. Returns:
  726. A var representing the equality comparison.
  727. """
  728. for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
  729. if not isinstance(other, Var) and other in python_types:
  730. return self.compare("===", Var.create(js_type, _var_is_string=True)) # type: ignore
  731. return self.compare("===", other)
  732. def __ne__(self, other: Union[Var, Type]) -> Var:
  733. """Perform an inequality comparison.
  734. Args:
  735. other: The other var to compare with.
  736. Returns:
  737. A var representing the inequality comparison.
  738. """
  739. for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
  740. if not isinstance(other, Var) and other in python_types:
  741. return self.compare("!==", Var.create(js_type, _var_is_string=True)) # type: ignore
  742. return self.compare("!==", other)
  743. def __gt__(self, other: Var) -> Var:
  744. """Perform a greater than comparison.
  745. Args:
  746. other: The other var to compare with.
  747. Returns:
  748. A var representing the greater than comparison.
  749. """
  750. return self.compare(">", other)
  751. def __ge__(self, other: Var) -> Var:
  752. """Perform a greater than or equal to comparison.
  753. Args:
  754. other: The other var to compare with.
  755. Returns:
  756. A var representing the greater than or equal to comparison.
  757. """
  758. return self.compare(">=", other)
  759. def __lt__(self, other: Var) -> Var:
  760. """Perform a less than comparison.
  761. Args:
  762. other: The other var to compare with.
  763. Returns:
  764. A var representing the less than comparison.
  765. """
  766. return self.compare("<", other)
  767. def __le__(self, other: Var) -> Var:
  768. """Perform a less than or equal to comparison.
  769. Args:
  770. other: The other var to compare with.
  771. Returns:
  772. A var representing the less than or equal to comparison.
  773. """
  774. return self.compare("<=", other)
  775. def __add__(self, other: Var, flip=False) -> Var:
  776. """Add two vars.
  777. Args:
  778. other: The other var to add.
  779. flip: Whether to flip operands.
  780. Returns:
  781. A var representing the sum.
  782. """
  783. other_type = other._var_type if isinstance(other, Var) else type(other)
  784. # For list-list addition, javascript concatenates the content of the lists instead of
  785. # merging the list, and for that reason we use the spread operator available through spreadArraysOrObjects
  786. # utility function
  787. if (
  788. types.get_base_class(self._var_type) == list
  789. and types.get_base_class(other_type) == list
  790. ):
  791. return self.operation(
  792. ",", other, fn="spreadArraysOrObjects", flip=flip
  793. )._replace(
  794. merge_var_data=VarData(
  795. imports={
  796. f"/{constants.Dirs.STATE_PATH}": [
  797. ImportVar(tag="spreadArraysOrObjects")
  798. ]
  799. },
  800. ),
  801. )
  802. return self.operation("+", other, flip=flip)
  803. def __radd__(self, other: Var) -> Var:
  804. """Add two vars.
  805. Args:
  806. other: The other var to add.
  807. Returns:
  808. A var representing the sum.
  809. """
  810. return self.__add__(other=other, flip=True)
  811. def __sub__(self, other: Var) -> Var:
  812. """Subtract two vars.
  813. Args:
  814. other: The other var to subtract.
  815. Returns:
  816. A var representing the difference.
  817. """
  818. return self.operation("-", other)
  819. def __rsub__(self, other: Var) -> Var:
  820. """Subtract two vars.
  821. Args:
  822. other: The other var to subtract.
  823. Returns:
  824. A var representing the difference.
  825. """
  826. return self.operation("-", other, flip=True)
  827. def __mul__(self, other: Var, flip=True) -> Var:
  828. """Multiply two vars.
  829. Args:
  830. other: The other var to multiply.
  831. flip: Whether to flip operands
  832. Returns:
  833. A var representing the product.
  834. """
  835. other_type = other._var_type if isinstance(other, Var) else type(other)
  836. # For str-int multiplication, we use the repeat function.
  837. # i.e "hello" * 2 is equivalent to "hello".repeat(2) in js.
  838. if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
  839. (int, str),
  840. (str, int),
  841. ]:
  842. return self.operation(other=other, fn="repeat", invoke_fn=True)
  843. # For list-int multiplication, we use the Array function.
  844. # i.e ["hello"] * 2 is equivalent to Array(2).fill().map(() => ["hello"]).flat() in js.
  845. if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
  846. (int, list),
  847. (list, int),
  848. ]:
  849. other_name = other._var_full_name if isinstance(other, Var) else other
  850. name = f"Array({other_name}).fill().map(() => {self._var_full_name}).flat()"
  851. return self._replace(
  852. _var_name=name,
  853. _var_type=str,
  854. _var_is_string=False,
  855. _var_full_name_needs_state_prefix=False,
  856. )
  857. return self.operation("*", other)
  858. def __rmul__(self, other: Var) -> Var:
  859. """Multiply two vars.
  860. Args:
  861. other: The other var to multiply.
  862. Returns:
  863. A var representing the product.
  864. """
  865. return self.__mul__(other=other, flip=True)
  866. def __pow__(self, other: Var) -> Var:
  867. """Raise a var to a power.
  868. Args:
  869. other: The power to raise to.
  870. Returns:
  871. A var representing the power.
  872. """
  873. return self.operation(",", other, fn="Math.pow")
  874. def __rpow__(self, other: Var) -> Var:
  875. """Raise a var to a power.
  876. Args:
  877. other: The power to raise to.
  878. Returns:
  879. A var representing the power.
  880. """
  881. return self.operation(",", other, flip=True, fn="Math.pow")
  882. def __truediv__(self, other: Var) -> Var:
  883. """Divide two vars.
  884. Args:
  885. other: The other var to divide.
  886. Returns:
  887. A var representing the quotient.
  888. """
  889. return self.operation("/", other)
  890. def __rtruediv__(self, other: Var) -> Var:
  891. """Divide two vars.
  892. Args:
  893. other: The other var to divide.
  894. Returns:
  895. A var representing the quotient.
  896. """
  897. return self.operation("/", other, flip=True)
  898. def __floordiv__(self, other: Var) -> Var:
  899. """Divide two vars.
  900. Args:
  901. other: The other var to divide.
  902. Returns:
  903. A var representing the quotient.
  904. """
  905. return self.operation("/", other, fn="Math.floor")
  906. def __mod__(self, other: Var) -> Var:
  907. """Get the remainder of two vars.
  908. Args:
  909. other: The other var to divide.
  910. Returns:
  911. A var representing the remainder.
  912. """
  913. return self.operation("%", other)
  914. def __rmod__(self, other: Var) -> Var:
  915. """Get the remainder of two vars.
  916. Args:
  917. other: The other var to divide.
  918. Returns:
  919. A var representing the remainder.
  920. """
  921. return self.operation("%", other, flip=True)
  922. def __and__(self, other: Var) -> Var:
  923. """Perform a logical and.
  924. Args:
  925. other: The other var to perform the logical AND with.
  926. Returns:
  927. A var representing the logical AND.
  928. Note:
  929. This method provides behavior specific to JavaScript, where it returns the JavaScript
  930. equivalent code (using the '&&' operator) of a logical AND operation.
  931. In JavaScript, the
  932. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  933. by returning the equivalent code as a Var instance.
  934. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  935. it challenging to override the behavior entirely.
  936. Therefore, this method leverages the
  937. bitwise AND '__and__' operator for custom JavaScript-like behavior.
  938. Example:
  939. >>> var1 = Var.create(True)
  940. >>> var2 = Var.create(False)
  941. >>> js_code = var1 & var2
  942. >>> print(js_code._var_full_name)
  943. '(true && false)'
  944. """
  945. return self.operation("&&", other, type_=bool)
  946. def __rand__(self, other: Var) -> Var:
  947. """Perform a logical and.
  948. Args:
  949. other: The other var to perform the logical AND with.
  950. Returns:
  951. A var representing the logical AND.
  952. Note:
  953. This method provides behavior specific to JavaScript, where it returns the JavaScript
  954. equivalent code (using the '&&' operator) of a logical AND operation.
  955. In JavaScript, the
  956. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  957. by returning the equivalent code as a Var instance.
  958. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  959. it challenging to override the behavior entirely.
  960. Therefore, this method leverages the
  961. bitwise AND '__rand__' operator for custom JavaScript-like behavior.
  962. Example:
  963. >>> var1 = Var.create(True)
  964. >>> var2 = Var.create(False)
  965. >>> js_code = var1 & var2
  966. >>> print(js_code._var_full_name)
  967. '(false && true)'
  968. """
  969. return self.operation("&&", other, type_=bool, flip=True)
  970. def __or__(self, other: Var) -> Var:
  971. """Perform a logical or.
  972. Args:
  973. other: The other var to perform the logical or with.
  974. Returns:
  975. A var representing the logical or.
  976. Note:
  977. This method provides behavior specific to JavaScript, where it returns the JavaScript
  978. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  979. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  980. by returning the equivalent code as a Var instance.
  981. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  982. it challenging to override the behavior entirely. Therefore, this method leverages the
  983. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  984. Example:
  985. >>> var1 = Var.create(True)
  986. >>> var2 = Var.create(False)
  987. >>> js_code = var1 | var2
  988. >>> print(js_code._var_full_name)
  989. '(true || false)'
  990. """
  991. return self.operation("||", other, type_=bool)
  992. def __ror__(self, other: Var) -> Var:
  993. """Perform a logical or.
  994. Args:
  995. other: The other var to perform the logical or with.
  996. Returns:
  997. A var representing the logical or.
  998. Note:
  999. This method provides behavior specific to JavaScript, where it returns the JavaScript
  1000. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  1001. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  1002. by returning the equivalent code as a Var instance.
  1003. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  1004. it challenging to override the behavior entirely. Therefore, this method leverages the
  1005. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  1006. Example:
  1007. >>> var1 = Var.create(True)
  1008. >>> var2 = Var.create(False)
  1009. >>> js_code = var1 | var2
  1010. >>> print(js_code)
  1011. 'false || true'
  1012. """
  1013. return self.operation("||", other, type_=bool, flip=True)
  1014. def __contains__(self, _: Any) -> Var:
  1015. """Override the 'in' operator to alert the user that it is not supported.
  1016. Raises:
  1017. TypeError: the operation is not supported
  1018. """
  1019. raise TypeError(
  1020. "'in' operator not supported for Var types, use Var.contains() instead."
  1021. )
  1022. def contains(self, other: Any) -> Var:
  1023. """Check if a var contains the object `other`.
  1024. Args:
  1025. other: The object to check.
  1026. Raises:
  1027. TypeError: If the var is not a valid type: dict, list, tuple or str.
  1028. Returns:
  1029. A var representing the contain check.
  1030. """
  1031. if not (types._issubclass(self._var_type, Union[dict, list, tuple, str])):
  1032. raise TypeError(
  1033. f"Var {self._var_full_name} of type {self._var_type} does not support contains check."
  1034. )
  1035. method = (
  1036. "hasOwnProperty"
  1037. if types.get_base_class(self._var_type) == dict
  1038. else "includes"
  1039. )
  1040. if isinstance(other, str):
  1041. other = Var.create(json.dumps(other), _var_is_string=True)
  1042. elif not isinstance(other, Var):
  1043. other = Var.create(other)
  1044. if types._issubclass(self._var_type, Dict):
  1045. return self._replace(
  1046. _var_name=f"{self._var_name}.{method}({other._var_full_name})",
  1047. _var_type=bool,
  1048. _var_is_string=False,
  1049. merge_var_data=other._var_data,
  1050. )
  1051. else: # str, list, tuple
  1052. # For strings, the left operand must be a string.
  1053. if types._issubclass(self._var_type, str) and not types._issubclass(
  1054. other._var_type, str
  1055. ):
  1056. raise TypeError(
  1057. f"'in <string>' requires string as left operand, not {other._var_type}"
  1058. )
  1059. return self._replace(
  1060. _var_name=f"{self._var_name}.includes({other._var_full_name})",
  1061. _var_type=bool,
  1062. _var_is_string=False,
  1063. merge_var_data=other._var_data,
  1064. )
  1065. def reverse(self) -> Var:
  1066. """Reverse a list var.
  1067. Raises:
  1068. TypeError: If the var is not a list.
  1069. Returns:
  1070. A var with the reversed list.
  1071. """
  1072. if not types._issubclass(self._var_type, list):
  1073. raise TypeError(f"Cannot reverse non-list var {self._var_full_name}.")
  1074. return self._replace(
  1075. _var_name=f"[...{self._var_full_name}].reverse()",
  1076. _var_is_string=False,
  1077. _var_full_name_needs_state_prefix=False,
  1078. )
  1079. def lower(self) -> Var:
  1080. """Convert a string var to lowercase.
  1081. Returns:
  1082. A var with the lowercase string.
  1083. Raises:
  1084. TypeError: If the var is not a string.
  1085. """
  1086. if not types._issubclass(self._var_type, str):
  1087. raise TypeError(
  1088. f"Cannot convert non-string var {self._var_full_name} to lowercase."
  1089. )
  1090. return self._replace(
  1091. _var_name=f"{self._var_name}.toLowerCase()",
  1092. _var_is_string=False,
  1093. _var_type=str,
  1094. )
  1095. def upper(self) -> Var:
  1096. """Convert a string var to uppercase.
  1097. Returns:
  1098. A var with the uppercase string.
  1099. Raises:
  1100. TypeError: If the var is not a string.
  1101. """
  1102. if not types._issubclass(self._var_type, str):
  1103. raise TypeError(
  1104. f"Cannot convert non-string var {self._var_full_name} to uppercase."
  1105. )
  1106. return self._replace(
  1107. _var_name=f"{self._var_name}.toUpperCase()",
  1108. _var_is_string=False,
  1109. _var_type=str,
  1110. )
  1111. def strip(self, other: str | Var[str] = " ") -> Var:
  1112. """Strip a string var.
  1113. Args:
  1114. other: The string to strip the var with.
  1115. Returns:
  1116. A var with the stripped string.
  1117. Raises:
  1118. TypeError: If the var is not a string.
  1119. """
  1120. if not types._issubclass(self._var_type, str):
  1121. raise TypeError(f"Cannot strip non-string var {self._var_full_name}.")
  1122. other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
  1123. return self._replace(
  1124. _var_name=f"{self._var_name}.replace(/^${other._var_full_name}|${other._var_full_name}$/g, '')",
  1125. _var_is_string=False,
  1126. merge_var_data=other._var_data,
  1127. )
  1128. def split(self, other: str | Var[str] = " ") -> Var:
  1129. """Split a string var into a list.
  1130. Args:
  1131. other: The string to split the var with.
  1132. Returns:
  1133. A var with the list.
  1134. Raises:
  1135. TypeError: If the var is not a string.
  1136. """
  1137. if not types._issubclass(self._var_type, str):
  1138. raise TypeError(f"Cannot split non-string var {self._var_full_name}.")
  1139. other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
  1140. return self._replace(
  1141. _var_name=f"{self._var_name}.split({other._var_full_name})",
  1142. _var_is_string=False,
  1143. _var_type=list[str],
  1144. merge_var_data=other._var_data,
  1145. )
  1146. def join(self, other: str | Var[str] | None = None) -> Var:
  1147. """Join a list var into a string.
  1148. Args:
  1149. other: The string to join the list with.
  1150. Returns:
  1151. A var with the string.
  1152. Raises:
  1153. TypeError: If the var is not a list.
  1154. """
  1155. if not types._issubclass(self._var_type, list):
  1156. raise TypeError(f"Cannot join non-list var {self._var_full_name}.")
  1157. if other is None:
  1158. other = Var.create_safe('""')
  1159. if isinstance(other, str):
  1160. other = Var.create_safe(json.dumps(other))
  1161. else:
  1162. other = Var.create_safe(other)
  1163. return self._replace(
  1164. _var_name=f"{self._var_name}.join({other._var_full_name})",
  1165. _var_is_string=False,
  1166. _var_type=str,
  1167. merge_var_data=other._var_data,
  1168. )
  1169. def foreach(self, fn: Callable) -> Var:
  1170. """Return a list of components. after doing a foreach on this var.
  1171. Args:
  1172. fn: The function to call on each component.
  1173. Returns:
  1174. A var representing foreach operation.
  1175. Raises:
  1176. TypeError: If the var is not a list.
  1177. """
  1178. inner_types = get_args(self._var_type)
  1179. if not inner_types:
  1180. raise TypeError(
  1181. f"Cannot foreach over non-sequence var {self._var_full_name} of type {self._var_type}."
  1182. )
  1183. arg = BaseVar(
  1184. _var_name=get_unique_variable_name(),
  1185. _var_type=inner_types[0],
  1186. )
  1187. index = BaseVar(
  1188. _var_name=get_unique_variable_name(),
  1189. _var_type=int,
  1190. )
  1191. fn_signature = inspect.signature(fn)
  1192. fn_args = (arg, index)
  1193. fn_ret = fn(*fn_args[: len(fn_signature.parameters)])
  1194. return self._replace(
  1195. _var_name=f"{self._var_full_name}.map(({arg._var_name}, {index._var_name}) => {fn_ret})",
  1196. _var_is_string=False,
  1197. )
  1198. @classmethod
  1199. def range(
  1200. cls,
  1201. v1: Var | int = 0,
  1202. v2: Var | int | None = None,
  1203. step: Var | int | None = None,
  1204. ) -> Var:
  1205. """Return an iterator over indices from v1 to v2 (or 0 to v1).
  1206. Args:
  1207. v1: The start of the range or end of range if v2 is not given.
  1208. v2: The end of the range.
  1209. step: The number of numbers between each item.
  1210. Returns:
  1211. A var representing range operation.
  1212. Raises:
  1213. TypeError: If the var is not an int.
  1214. """
  1215. if not isinstance(v1, Var):
  1216. v1 = Var.create_safe(v1)
  1217. if v1._var_type != int:
  1218. raise TypeError(f"Cannot get range on non-int var {v1._var_full_name}.")
  1219. if not isinstance(v2, Var):
  1220. v2 = Var.create(v2)
  1221. if v2 is None:
  1222. v2 = Var.create_safe("undefined")
  1223. elif v2._var_type != int:
  1224. raise TypeError(f"Cannot get range on non-int var {v2._var_full_name}.")
  1225. if not isinstance(step, Var):
  1226. step = Var.create(step)
  1227. if step is None:
  1228. step = Var.create_safe(1)
  1229. elif step._var_type != int:
  1230. raise TypeError(f"Cannot get range on non-int var {step._var_full_name}.")
  1231. return BaseVar(
  1232. _var_name=f"Array.from(range({v1._var_full_name}, {v2._var_full_name}, {step._var_name}))",
  1233. _var_type=list[int],
  1234. _var_is_local=False,
  1235. _var_data=VarData.merge(
  1236. v1._var_data,
  1237. v2._var_data,
  1238. step._var_data,
  1239. VarData(
  1240. imports={
  1241. "/utils/helpers/range.js": [
  1242. ImportVar(tag="range", is_default=True),
  1243. ],
  1244. },
  1245. ),
  1246. ),
  1247. )
  1248. def to(self, type_: Type) -> Var:
  1249. """Convert the type of the var.
  1250. Args:
  1251. type_: The type to convert to.
  1252. Returns:
  1253. The converted var.
  1254. """
  1255. return self._replace(_var_type=type_)
  1256. def as_ref(self) -> Var:
  1257. """Convert the var to a ref.
  1258. Returns:
  1259. The var as a ref.
  1260. """
  1261. return self._replace(
  1262. _var_name=f"refs['{self._var_full_name}']",
  1263. _var_is_local=True,
  1264. _var_is_string=False,
  1265. _var_full_name_needs_state_prefix=False,
  1266. merge_var_data=VarData(
  1267. imports={
  1268. f"/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")],
  1269. },
  1270. ),
  1271. )
  1272. @property
  1273. def _var_full_name(self) -> str:
  1274. """Get the full name of the var.
  1275. Returns:
  1276. The full name of the var.
  1277. """
  1278. if not self._var_full_name_needs_state_prefix:
  1279. return self._var_name
  1280. return (
  1281. self._var_name
  1282. if self._var_data is None or self._var_data.state == ""
  1283. else ".".join(
  1284. [format.format_state_name(self._var_data.state), self._var_name]
  1285. )
  1286. )
  1287. def _var_set_state(self, state: Type[BaseState] | str) -> Any:
  1288. """Set the state of the var.
  1289. Args:
  1290. state: The state to set or the full name of the state.
  1291. Returns:
  1292. The var with the set state.
  1293. """
  1294. state_name = state if isinstance(state, str) else state.get_full_name()
  1295. new_var_data = VarData(
  1296. state=state_name,
  1297. hooks={
  1298. "const {0} = useContext(StateContexts.{0})".format(
  1299. format.format_state_name(state_name)
  1300. )
  1301. },
  1302. imports={
  1303. f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  1304. "react": [ImportVar(tag="useContext")],
  1305. },
  1306. )
  1307. self._var_data = VarData.merge(self._var_data, new_var_data)
  1308. self._var_full_name_needs_state_prefix = True
  1309. return self
  1310. @property
  1311. def _var_state(self) -> str:
  1312. """Compat method for getting the state.
  1313. Returns:
  1314. The state name associated with the var.
  1315. """
  1316. return self._var_data.state if self._var_data else ""
  1317. @property
  1318. def _var_name_unwrapped(self) -> str:
  1319. """Get the var str without wrapping in curly braces.
  1320. Returns:
  1321. The str var without the wrapped curly braces
  1322. """
  1323. from reflex.style import Style
  1324. type_ = (
  1325. get_origin(self._var_type)
  1326. if types.is_generic_alias(self._var_type)
  1327. else self._var_type
  1328. )
  1329. wrapped_var = str(self)
  1330. return (
  1331. wrapped_var
  1332. if not self._var_state
  1333. and types._issubclass(type_, dict)
  1334. or types._issubclass(type_, Style)
  1335. else wrapped_var.strip("{}")
  1336. )
  1337. # Allow automatic serialization of Var within JSON structures
  1338. serializers.serializer(_encode_var)
  1339. @dataclasses.dataclass(
  1340. eq=False,
  1341. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1342. )
  1343. class BaseVar(Var):
  1344. """A base (non-computed) var of the app state."""
  1345. # The name of the var.
  1346. _var_name: str = dataclasses.field()
  1347. # The type of the var.
  1348. _var_type: Type = dataclasses.field(default=Any)
  1349. # Whether this is a local javascript variable.
  1350. _var_is_local: bool = dataclasses.field(default=False)
  1351. # Whether the var is a string literal.
  1352. _var_is_string: bool = dataclasses.field(default=False)
  1353. # _var_full_name should be prefixed with _var_state
  1354. _var_full_name_needs_state_prefix: bool = dataclasses.field(default=False)
  1355. # Extra metadata associated with the Var
  1356. _var_data: Optional[VarData] = dataclasses.field(default=None)
  1357. def __hash__(self) -> int:
  1358. """Define a hash function for a var.
  1359. Returns:
  1360. The hash of the var.
  1361. """
  1362. return hash((self._var_name, str(self._var_type)))
  1363. def get_default_value(self) -> Any:
  1364. """Get the default value of the var.
  1365. Returns:
  1366. The default value of the var.
  1367. Raises:
  1368. ImportError: If the var is a dataframe and pandas is not installed.
  1369. """
  1370. if types.is_optional(self._var_type):
  1371. return None
  1372. type_ = (
  1373. get_origin(self._var_type)
  1374. if types.is_generic_alias(self._var_type)
  1375. else self._var_type
  1376. )
  1377. if type_ is Literal:
  1378. args = get_args(self._var_type)
  1379. return args[0] if args else None
  1380. if issubclass(type_, str):
  1381. return ""
  1382. if issubclass(type_, types.get_args(Union[int, float])):
  1383. return 0
  1384. if issubclass(type_, bool):
  1385. return False
  1386. if issubclass(type_, list):
  1387. return []
  1388. if issubclass(type_, dict):
  1389. return {}
  1390. if issubclass(type_, tuple):
  1391. return ()
  1392. if types.is_dataframe(type_):
  1393. try:
  1394. import pandas as pd
  1395. return pd.DataFrame()
  1396. except ImportError as e:
  1397. raise ImportError(
  1398. "Please install pandas to use dataframes in your app."
  1399. ) from e
  1400. return set() if issubclass(type_, set) else None
  1401. def get_setter_name(self, include_state: bool = True) -> str:
  1402. """Get the name of the var's generated setter function.
  1403. Args:
  1404. include_state: Whether to include the state name in the setter name.
  1405. Returns:
  1406. The name of the setter function.
  1407. """
  1408. setter = constants.SETTER_PREFIX + self._var_name
  1409. if self._var_data is None:
  1410. return setter
  1411. if not include_state or self._var_data.state == "":
  1412. return setter
  1413. return ".".join((self._var_data.state, setter))
  1414. def get_setter(self) -> Callable[[BaseState, Any], None]:
  1415. """Get the var's setter function.
  1416. Returns:
  1417. A function that that creates a setter for the var.
  1418. """
  1419. def setter(state: BaseState, value: Any):
  1420. """Get the setter for the var.
  1421. Args:
  1422. state: The state within which we add the setter function.
  1423. value: The value to set.
  1424. """
  1425. if self._var_type in [int, float]:
  1426. try:
  1427. value = self._var_type(value)
  1428. setattr(state, self._var_name, value)
  1429. except ValueError:
  1430. console.warn(
  1431. f"{self._var_name}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
  1432. )
  1433. else:
  1434. setattr(state, self._var_name, value)
  1435. setter.__qualname__ = self.get_setter_name()
  1436. return setter
  1437. @dataclasses.dataclass(init=False, eq=False)
  1438. class ComputedVar(Var, property):
  1439. """A field with computed getters."""
  1440. # Whether to track dependencies and cache computed values
  1441. _cache: bool = dataclasses.field(default=False)
  1442. def __init__(
  1443. self,
  1444. fget: Callable[[BaseState], Any],
  1445. fset: Callable[[BaseState, Any], None] | None = None,
  1446. fdel: Callable[[BaseState], Any] | None = None,
  1447. doc: str | None = None,
  1448. **kwargs,
  1449. ):
  1450. """Initialize a ComputedVar.
  1451. Args:
  1452. fget: The getter function.
  1453. fset: The setter function.
  1454. fdel: The deleter function.
  1455. doc: The docstring.
  1456. **kwargs: additional attributes to set on the instance
  1457. """
  1458. property.__init__(self, fget, fset, fdel, doc)
  1459. kwargs["_var_name"] = kwargs.pop("_var_name", fget.__name__)
  1460. kwargs["_var_type"] = kwargs.pop("_var_type", self._determine_var_type())
  1461. BaseVar.__init__(self, **kwargs) # type: ignore
  1462. @property
  1463. def _cache_attr(self) -> str:
  1464. """Get the attribute used to cache the value on the instance.
  1465. Returns:
  1466. An attribute name.
  1467. """
  1468. return f"__cached_{self._var_name}"
  1469. def __get__(self, instance, owner):
  1470. """Get the ComputedVar value.
  1471. If the value is already cached on the instance, return the cached value.
  1472. Args:
  1473. instance: the instance of the class accessing this computed var.
  1474. owner: the class that this descriptor is attached to.
  1475. Returns:
  1476. The value of the var for the given instance.
  1477. """
  1478. if instance is None or not self._cache:
  1479. return super().__get__(instance, owner)
  1480. # handle caching
  1481. if not hasattr(instance, self._cache_attr):
  1482. setattr(instance, self._cache_attr, super().__get__(instance, owner))
  1483. return getattr(instance, self._cache_attr)
  1484. def _deps(
  1485. self,
  1486. objclass: Type,
  1487. obj: FunctionType | CodeType | None = None,
  1488. self_name: Optional[str] = None,
  1489. ) -> set[str]:
  1490. """Determine var dependencies of this ComputedVar.
  1491. Save references to attributes accessed on "self". Recursively called
  1492. when the function makes a method call on "self" or define comprehensions
  1493. or nested functions that may reference "self".
  1494. Args:
  1495. objclass: the class obj this ComputedVar is attached to.
  1496. obj: the object to disassemble (defaults to the fget function).
  1497. self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
  1498. Returns:
  1499. A set of variable names accessed by the given obj.
  1500. """
  1501. d = set()
  1502. if obj is None:
  1503. if self.fget is not None:
  1504. obj = cast(FunctionType, self.fget)
  1505. else:
  1506. return set()
  1507. with contextlib.suppress(AttributeError):
  1508. # unbox functools.partial
  1509. obj = cast(FunctionType, obj.func) # type: ignore
  1510. with contextlib.suppress(AttributeError):
  1511. # unbox EventHandler
  1512. obj = cast(FunctionType, obj.fn) # type: ignore
  1513. if self_name is None and isinstance(obj, FunctionType):
  1514. try:
  1515. # the first argument to the function is the name of "self" arg
  1516. self_name = obj.__code__.co_varnames[0]
  1517. except (AttributeError, IndexError):
  1518. self_name = None
  1519. if self_name is None:
  1520. # cannot reference attributes on self if method takes no args
  1521. return set()
  1522. self_is_top_of_stack = False
  1523. for instruction in dis.get_instructions(obj):
  1524. if (
  1525. instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
  1526. and instruction.argval == self_name
  1527. ):
  1528. # bytecode loaded the class instance to the top of stack, next load instruction
  1529. # is referencing an attribute on self
  1530. self_is_top_of_stack = True
  1531. continue
  1532. if self_is_top_of_stack and instruction.opname in (
  1533. "LOAD_ATTR",
  1534. "LOAD_METHOD",
  1535. ):
  1536. try:
  1537. ref_obj = getattr(objclass, instruction.argval)
  1538. except Exception:
  1539. ref_obj = None
  1540. if callable(ref_obj):
  1541. # recurse into callable attributes
  1542. d.update(
  1543. self._deps(
  1544. objclass=objclass,
  1545. obj=ref_obj,
  1546. )
  1547. )
  1548. else:
  1549. # normal attribute access
  1550. d.add(instruction.argval)
  1551. elif instruction.opname == "LOAD_CONST" and isinstance(
  1552. instruction.argval, CodeType
  1553. ):
  1554. # recurse into nested functions / comprehensions, which can reference
  1555. # instance attributes from the outer scope
  1556. d.update(
  1557. self._deps(
  1558. objclass=objclass,
  1559. obj=instruction.argval,
  1560. self_name=self_name,
  1561. )
  1562. )
  1563. self_is_top_of_stack = False
  1564. return d
  1565. def mark_dirty(self, instance) -> None:
  1566. """Mark this ComputedVar as dirty.
  1567. Args:
  1568. instance: the state instance that needs to recompute the value.
  1569. """
  1570. with contextlib.suppress(AttributeError):
  1571. delattr(instance, self._cache_attr)
  1572. def _determine_var_type(self) -> Type:
  1573. """Get the type of the var.
  1574. Returns:
  1575. The type of the var.
  1576. """
  1577. hints = get_type_hints(self.fget)
  1578. if "return" in hints:
  1579. return hints["return"]
  1580. return Any
  1581. def cached_var(fget: Callable[[Any], Any]) -> ComputedVar:
  1582. """A field with computed getter that tracks other state dependencies.
  1583. The cached_var will only be recalculated when other state vars that it
  1584. depends on are modified.
  1585. Args:
  1586. fget: the function that calculates the variable value.
  1587. Returns:
  1588. ComputedVar that is recomputed when dependencies change.
  1589. """
  1590. cvar = ComputedVar(fget=fget)
  1591. cvar._cache = True
  1592. return cvar
  1593. class CallableVar(BaseVar):
  1594. """Decorate a Var-returning function to act as both a Var and a function.
  1595. This is used as a compatibility shim for replacing Var objects in the
  1596. API with functions that return a family of Var.
  1597. """
  1598. def __init__(self, fn: Callable[..., BaseVar]):
  1599. """Initialize a CallableVar.
  1600. Args:
  1601. fn: The function to decorate (must return Var)
  1602. """
  1603. self.fn = fn
  1604. default_var = fn()
  1605. super().__init__(**dataclasses.asdict(default_var))
  1606. def __call__(self, *args, **kwargs) -> BaseVar:
  1607. """Call the decorated function.
  1608. Args:
  1609. *args: The args to pass to the function.
  1610. **kwargs: The kwargs to pass to the function.
  1611. Returns:
  1612. The Var returned from calling the function.
  1613. """
  1614. return self.fn(*args, **kwargs)