vars.py 60 KB

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