vars.py 59 KB

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