vars.py 64 KB

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