vars.py 67 KB

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