vars.py 64 KB

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