vars.py 58 KB

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