vars.py 63 KB

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