vars.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. """Define a state var."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dis
  5. import json
  6. import random
  7. import string
  8. from abc import ABC
  9. from types import CodeType, FunctionType
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. Dict,
  15. List,
  16. Optional,
  17. Tuple,
  18. Type,
  19. Union,
  20. _GenericAlias, # type: ignore
  21. cast,
  22. get_type_hints,
  23. )
  24. from pydantic.fields import ModelField
  25. from reflex import constants
  26. from reflex.base import Base
  27. from reflex.utils import console, format, types
  28. from reflex.utils.serializers import serialize
  29. if TYPE_CHECKING:
  30. from reflex.state import State
  31. # Set of unique variable names.
  32. USED_VARIABLES = set()
  33. # Supported operators for all types.
  34. ALL_OPS = ["==", "!=", "!==", "===", "&&", "||"]
  35. # Delimiters used between function args or operands.
  36. DELIMITERS = [","]
  37. # Mapping of valid operations for different type combinations.
  38. OPERATION_MAPPING = {
  39. (int, int): {
  40. "+",
  41. "-",
  42. "/",
  43. "//",
  44. "*",
  45. "%",
  46. "**",
  47. ">",
  48. "<",
  49. "<=",
  50. ">=",
  51. "|",
  52. "&",
  53. },
  54. (int, str): {"*"},
  55. (int, list): {"*"},
  56. (str, str): {"+", ">", "<", "<=", ">="},
  57. (float, float): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  58. (float, int): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  59. (list, list): {"+", ">", "<", "<=", ">="},
  60. }
  61. def get_unique_variable_name() -> str:
  62. """Get a unique variable name.
  63. Returns:
  64. The unique variable name.
  65. """
  66. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  67. if name not in USED_VARIABLES:
  68. USED_VARIABLES.add(name)
  69. return name
  70. return get_unique_variable_name()
  71. class Var(ABC):
  72. """An abstract var."""
  73. # The name of the var.
  74. name: str
  75. # The type of the var.
  76. type_: Type
  77. # The name of the enclosing state.
  78. state: str = ""
  79. # Whether this is a local javascript variable.
  80. is_local: bool = False
  81. # Whether the var is a string literal.
  82. is_string: bool = False
  83. @classmethod
  84. def create(
  85. cls, value: Any, is_local: bool = True, is_string: bool = False
  86. ) -> Var | None:
  87. """Create a var from a value.
  88. Args:
  89. value: The value to create the var from.
  90. is_local: Whether the var is local.
  91. is_string: Whether the var is a string literal.
  92. Returns:
  93. The var.
  94. Raises:
  95. TypeError: If the value is JSON-unserializable.
  96. """
  97. # Check for none values.
  98. if value is None:
  99. return None
  100. # If the value is already a var, do nothing.
  101. if isinstance(value, Var):
  102. return value
  103. # Try to serialize the value.
  104. type_ = type(value)
  105. name = serialize(value)
  106. if name is None:
  107. raise TypeError(
  108. f"No JSON serializer found for var {value} of type {type_}."
  109. )
  110. name = name if isinstance(name, str) else format.json_dumps(name)
  111. return BaseVar(name=name, type_=type_, is_local=is_local, is_string=is_string)
  112. @classmethod
  113. def create_safe(
  114. cls, value: Any, is_local: bool = True, is_string: bool = False
  115. ) -> Var:
  116. """Create a var from a value, guaranteeing that it is not None.
  117. Args:
  118. value: The value to create the var from.
  119. is_local: Whether the var is local.
  120. is_string: Whether the var is a string literal.
  121. Returns:
  122. The var.
  123. """
  124. var = cls.create(value, is_local=is_local, is_string=is_string)
  125. assert var is not None
  126. return var
  127. @classmethod
  128. def __class_getitem__(cls, type_: str) -> _GenericAlias:
  129. """Get a typed var.
  130. Args:
  131. type_: The type of the var.
  132. Returns:
  133. The var class item.
  134. """
  135. return _GenericAlias(cls, type_)
  136. def _decode(self) -> Any:
  137. """Decode Var as a python value.
  138. Note that Var with state set cannot be decoded python-side and will be
  139. returned as full_name.
  140. Returns:
  141. The decoded value or the Var name.
  142. """
  143. if self.state:
  144. return self.full_name
  145. if self.is_string:
  146. return self.name
  147. try:
  148. return json.loads(self.name)
  149. except ValueError:
  150. return self.name
  151. def equals(self, other: Var) -> bool:
  152. """Check if two vars are equal.
  153. Args:
  154. other: The other var to compare.
  155. Returns:
  156. Whether the vars are equal.
  157. """
  158. return (
  159. self.name == other.name
  160. and self.type_ == other.type_
  161. and self.state == other.state
  162. and self.is_local == other.is_local
  163. )
  164. def to_string(self, json: bool = True) -> Var:
  165. """Convert a var to a string.
  166. Args:
  167. json: Whether to convert to a JSON string.
  168. Returns:
  169. The stringified var.
  170. """
  171. fn = "JSON.stringify" if json else "String"
  172. return self.operation(fn=fn, type_=str)
  173. def __hash__(self) -> int:
  174. """Define a hash function for a var.
  175. Returns:
  176. The hash of the var.
  177. """
  178. return hash((self.name, str(self.type_)))
  179. def __str__(self) -> str:
  180. """Wrap the var so it can be used in templates.
  181. Returns:
  182. The wrapped var, i.e. {state.var}.
  183. """
  184. out = self.full_name if self.is_local else format.wrap(self.full_name, "{")
  185. if self.is_string:
  186. out = format.format_string(out)
  187. return out
  188. def __bool__(self) -> bool:
  189. """Raise exception if using Var in a boolean context.
  190. Raises:
  191. TypeError: when attempting to bool-ify the Var.
  192. """
  193. raise TypeError(
  194. f"Cannot convert Var {self.full_name!r} to bool for use with `if`, `and`, `or`, and `not`. "
  195. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  196. )
  197. def __iter__(self) -> Any:
  198. """Raise exception if using Var in an iterable context.
  199. Raises:
  200. TypeError: when attempting to iterate over the Var.
  201. """
  202. raise TypeError(
  203. f"Cannot iterate over Var {self.full_name!r}. Instead use `rx.foreach`."
  204. )
  205. def __format__(self, format_spec: str) -> str:
  206. """Format the var into a Javascript equivalent to an f-string.
  207. Args:
  208. format_spec: The format specifier (Ignored for now).
  209. Returns:
  210. The formatted var.
  211. """
  212. if self.is_local:
  213. return str(self)
  214. return f"${str(self)}"
  215. def __getitem__(self, i: Any) -> Var:
  216. """Index into a var.
  217. Args:
  218. i: The index to index into.
  219. Returns:
  220. The indexed var.
  221. Raises:
  222. TypeError: If the var is not indexable.
  223. """
  224. # Indexing is only supported for strings, lists, tuples, dicts, and dataframes.
  225. if not (
  226. types._issubclass(self.type_, Union[List, Dict, Tuple, str])
  227. or types.is_dataframe(self.type_)
  228. ):
  229. if self.type_ == Any:
  230. raise TypeError(
  231. "Could not index into var of type Any. (If you are trying to index into a state var, "
  232. "add the correct type annotation to the var.)"
  233. )
  234. raise TypeError(
  235. f"Var {self.name} of type {self.type_} does not support indexing."
  236. )
  237. # The type of the indexed var.
  238. type_ = Any
  239. # Convert any vars to local vars.
  240. if isinstance(i, Var):
  241. i = BaseVar(name=i.name, type_=i.type_, state=i.state, is_local=True)
  242. # Handle list/tuple/str indexing.
  243. if types._issubclass(self.type_, Union[List, Tuple, str]):
  244. # List/Tuple/String indices must be ints, slices, or vars.
  245. if (
  246. not isinstance(i, types.get_args(Union[int, slice, Var]))
  247. or isinstance(i, Var)
  248. and not i.type_ == int
  249. ):
  250. raise TypeError("Index must be an integer or an integer var.")
  251. # Handle slices first.
  252. if isinstance(i, slice):
  253. # Get the start and stop indices.
  254. start = i.start or 0
  255. stop = i.stop or "undefined"
  256. # Use the slice function.
  257. return BaseVar(
  258. name=f"{self.name}.slice({start}, {stop})",
  259. type_=self.type_,
  260. state=self.state,
  261. is_local=self.is_local,
  262. )
  263. # Get the type of the indexed var.
  264. type_ = (
  265. types.get_args(self.type_)[0]
  266. if types.is_generic_alias(self.type_)
  267. else Any
  268. )
  269. # Use `at` to support negative indices.
  270. return BaseVar(
  271. name=f"{self.name}.at({i})",
  272. type_=type_,
  273. state=self.state,
  274. is_local=self.is_local,
  275. )
  276. # Dictionary / dataframe indexing.
  277. # Tuples are currently not supported as indexes.
  278. if (
  279. (types._issubclass(self.type_, Dict) or types.is_dataframe(self.type_))
  280. and not isinstance(i, types.get_args(Union[int, str, float, Var]))
  281. ) or (
  282. isinstance(i, Var)
  283. and not types._issubclass(i.type_, types.get_args(Union[int, str, float]))
  284. ):
  285. raise TypeError(
  286. "Index must be one of the following types: int, str, int or str Var"
  287. )
  288. # Get the type of the indexed var.
  289. if isinstance(i, str):
  290. i = format.wrap(i, '"')
  291. type_ = (
  292. types.get_args(self.type_)[1] if types.is_generic_alias(self.type_) else Any
  293. )
  294. # Use normal indexing here.
  295. return BaseVar(
  296. name=f"{self.name}[{i}]",
  297. type_=type_,
  298. state=self.state,
  299. is_local=self.is_local,
  300. )
  301. def __getattribute__(self, name: str) -> Var:
  302. """Get a var attribute.
  303. Args:
  304. name: The name of the attribute.
  305. Returns:
  306. The var attribute.
  307. Raises:
  308. AttributeError: If the var is wrongly annotated or can't find attribute.
  309. TypeError: If an annotation to the var isn't provided.
  310. """
  311. try:
  312. return super().__getattribute__(name)
  313. except Exception as e:
  314. # Check if the attribute is one of the class fields.
  315. if not name.startswith("_"):
  316. if self.type_ == Any:
  317. raise TypeError(
  318. f"You must provide an annotation for the state var `{self.full_name}`. Annotation cannot be `{self.type_}`"
  319. ) from None
  320. if hasattr(self.type_, "__fields__") and name in self.type_.__fields__:
  321. type_ = self.type_.__fields__[name].outer_type_
  322. if isinstance(type_, ModelField):
  323. type_ = type_.type_
  324. return BaseVar(
  325. name=f"{self.name}.{name}",
  326. type_=type_,
  327. state=self.state,
  328. is_local=self.is_local,
  329. )
  330. raise AttributeError(
  331. f"The State var `{self.full_name}` has no attribute '{name}' or may have been annotated "
  332. f"wrongly.\n"
  333. f"original message: {e.args[0]}"
  334. ) from e
  335. def operation(
  336. self,
  337. op: str = "",
  338. other: Var | None = None,
  339. type_: Type | None = None,
  340. flip: bool = False,
  341. fn: str | None = None,
  342. invoke_fn: bool = False,
  343. ) -> Var:
  344. """Perform an operation on a var.
  345. Args:
  346. op: The operation to perform.
  347. other: The other var to perform the operation on.
  348. type_: The type of the operation result.
  349. flip: Whether to flip the order of the operation.
  350. fn: A function to apply to the operation.
  351. invoke_fn: Whether to invoke the function.
  352. Returns:
  353. The operation result.
  354. Raises:
  355. TypeError: If the operation between two operands is invalid.
  356. ValueError: If flip is set to true and value of operand is not provided
  357. """
  358. if isinstance(other, str):
  359. other = Var.create(json.dumps(other))
  360. else:
  361. other = Var.create(other)
  362. type_ = type_ or self.type_
  363. if other is None and flip:
  364. raise ValueError(
  365. "flip_operands cannot be set to True if the value of 'other' operand is not provided"
  366. )
  367. left_operand, right_operand = (other, self) if flip else (self, other)
  368. if other is not None:
  369. # check if the operation between operands is valid.
  370. if op and not self.is_valid_operation(
  371. types.get_base_class(left_operand.type_), # type: ignore
  372. types.get_base_class(right_operand.type_), # type: ignore
  373. op,
  374. ):
  375. raise TypeError(
  376. f"Unsupported Operand type(s) for {op}: `{left_operand.full_name}` of type {left_operand.type_.__name__} and `{right_operand.full_name}` of type {right_operand.type_.__name__}" # type: ignore
  377. )
  378. # apply function to operands
  379. if fn is not None:
  380. if invoke_fn:
  381. # invoke the function on left operand.
  382. operation_name = f"{left_operand.full_name}.{fn}({right_operand.full_name})" # type: ignore
  383. else:
  384. # pass the operands as arguments to the function.
  385. operation_name = f"{left_operand.full_name} {op} {right_operand.full_name}" # type: ignore
  386. operation_name = f"{fn}({operation_name})"
  387. else:
  388. # apply operator to operands (left operand <operator> right_operand)
  389. operation_name = f"{left_operand.full_name} {op} {right_operand.full_name}" # type: ignore
  390. operation_name = format.wrap(operation_name, "(")
  391. else:
  392. # apply operator to left operand (<operator> left_operand)
  393. operation_name = f"{op}{self.full_name}"
  394. # apply function to operands
  395. if fn is not None:
  396. operation_name = (
  397. f"{fn}({operation_name})"
  398. if not invoke_fn
  399. else f"{self.full_name}.{fn}()"
  400. )
  401. return BaseVar(
  402. name=operation_name,
  403. type_=type_,
  404. is_local=self.is_local,
  405. )
  406. @staticmethod
  407. def is_valid_operation(
  408. operand1_type: Type, operand2_type: Type, operator: str
  409. ) -> bool:
  410. """Check if an operation between two operands is valid.
  411. Args:
  412. operand1_type: Type of the operand
  413. operand2_type: Type of the second operand
  414. operator: The operator.
  415. Returns:
  416. Whether operation is valid or not
  417. """
  418. if operator in ALL_OPS or operator in DELIMITERS:
  419. return True
  420. # bools are subclasses of ints
  421. pair = tuple(
  422. sorted(
  423. [
  424. int if operand1_type == bool else operand1_type,
  425. int if operand2_type == bool else operand2_type,
  426. ],
  427. key=lambda x: x.__name__,
  428. )
  429. )
  430. return pair in OPERATION_MAPPING and operator in OPERATION_MAPPING[pair]
  431. def compare(self, op: str, other: Var) -> Var:
  432. """Compare two vars with inequalities.
  433. Args:
  434. op: The comparison operator.
  435. other: The other var to compare with.
  436. Returns:
  437. The comparison result.
  438. """
  439. return self.operation(op, other, bool)
  440. def __invert__(self) -> Var:
  441. """Invert a var.
  442. Returns:
  443. The inverted var.
  444. """
  445. return self.operation("!", type_=bool)
  446. def __neg__(self) -> Var:
  447. """Negate a var.
  448. Returns:
  449. The negated var.
  450. """
  451. return self.operation(fn="-")
  452. def __abs__(self) -> Var:
  453. """Get the absolute value of a var.
  454. Returns:
  455. A var with the absolute value.
  456. """
  457. return self.operation(fn="Math.abs")
  458. def length(self) -> Var:
  459. """Get the length of a list var.
  460. Returns:
  461. A var with the absolute value.
  462. Raises:
  463. TypeError: If the var is not a list.
  464. """
  465. if not types._issubclass(self.type_, List):
  466. raise TypeError(f"Cannot get length of non-list var {self}.")
  467. return BaseVar(
  468. name=f"{self.full_name}.length",
  469. type_=int,
  470. is_local=self.is_local,
  471. )
  472. def __eq__(self, other: Var) -> Var:
  473. """Perform an equality comparison.
  474. Args:
  475. other: The other var to compare with.
  476. Returns:
  477. A var representing the equality comparison.
  478. """
  479. return self.compare("===", other)
  480. def __ne__(self, other: Var) -> Var:
  481. """Perform an inequality comparison.
  482. Args:
  483. other: The other var to compare with.
  484. Returns:
  485. A var representing the inequality comparison.
  486. """
  487. return self.compare("!==", other)
  488. def __gt__(self, other: Var) -> Var:
  489. """Perform a greater than comparison.
  490. Args:
  491. other: The other var to compare with.
  492. Returns:
  493. A var representing the greater than comparison.
  494. """
  495. return self.compare(">", other)
  496. def __ge__(self, other: Var) -> Var:
  497. """Perform a greater than or equal to comparison.
  498. Args:
  499. other: The other var to compare with.
  500. Returns:
  501. A var representing the greater than or equal to comparison.
  502. """
  503. return self.compare(">=", other)
  504. def __lt__(self, other: Var) -> Var:
  505. """Perform a less than comparison.
  506. Args:
  507. other: The other var to compare with.
  508. Returns:
  509. A var representing the less than comparison.
  510. """
  511. return self.compare("<", other)
  512. def __le__(self, other: Var) -> Var:
  513. """Perform a less than or equal to comparison.
  514. Args:
  515. other: The other var to compare with.
  516. Returns:
  517. A var representing the less than or equal to comparison.
  518. """
  519. return self.compare("<=", other)
  520. def __add__(self, other: Var, flip=False) -> Var:
  521. """Add two vars.
  522. Args:
  523. other: The other var to add.
  524. flip: Whether to flip operands.
  525. Returns:
  526. A var representing the sum.
  527. """
  528. other_type = other.type_ if isinstance(other, Var) else type(other)
  529. # For list-list addition, javascript concatenates the content of the lists instead of
  530. # merging the list, and for that reason we use the spread operator available through spreadArraysOrObjects
  531. # utility function
  532. if (
  533. types.get_base_class(self.type_) == list
  534. and types.get_base_class(other_type) == list
  535. ):
  536. return self.operation(",", other, fn="spreadArraysOrObjects", flip=flip)
  537. return self.operation("+", other, flip=flip)
  538. def __radd__(self, other: Var) -> Var:
  539. """Add two vars.
  540. Args:
  541. other: The other var to add.
  542. Returns:
  543. A var representing the sum.
  544. """
  545. return self.__add__(other=other, flip=True)
  546. def __sub__(self, other: Var) -> Var:
  547. """Subtract two vars.
  548. Args:
  549. other: The other var to subtract.
  550. Returns:
  551. A var representing the difference.
  552. """
  553. return self.operation("-", other)
  554. def __rsub__(self, other: Var) -> Var:
  555. """Subtract two vars.
  556. Args:
  557. other: The other var to subtract.
  558. Returns:
  559. A var representing the difference.
  560. """
  561. return self.operation("-", other, flip=True)
  562. def __mul__(self, other: Var, flip=True) -> Var:
  563. """Multiply two vars.
  564. Args:
  565. other: The other var to multiply.
  566. flip: Whether to flip operands
  567. Returns:
  568. A var representing the product.
  569. """
  570. other_type = other.type_ if isinstance(other, Var) else type(other)
  571. # For str-int multiplication, we use the repeat function.
  572. # i.e "hello" * 2 is equivalent to "hello".repeat(2) in js.
  573. if (types.get_base_class(self.type_), types.get_base_class(other_type)) in [
  574. (int, str),
  575. (str, int),
  576. ]:
  577. return self.operation(other=other, fn="repeat", invoke_fn=True)
  578. # For list-int multiplication, we use the Array function.
  579. # i.e ["hello"] * 2 is equivalent to Array(2).fill().map(() => ["hello"]).flat() in js.
  580. if (types.get_base_class(self.type_), types.get_base_class(other_type)) in [
  581. (int, list),
  582. (list, int),
  583. ]:
  584. other_name = other.full_name if isinstance(other, Var) else other
  585. name = f"Array({other_name}).fill().map(() => {self.full_name}).flat()"
  586. return BaseVar(
  587. name=name,
  588. type_=str,
  589. is_local=self.is_local,
  590. )
  591. return self.operation("*", other)
  592. def __rmul__(self, other: Var) -> Var:
  593. """Multiply two vars.
  594. Args:
  595. other: The other var to multiply.
  596. Returns:
  597. A var representing the product.
  598. """
  599. return self.__mul__(other=other, flip=True)
  600. def __pow__(self, other: Var) -> Var:
  601. """Raise a var to a power.
  602. Args:
  603. other: The power to raise to.
  604. Returns:
  605. A var representing the power.
  606. """
  607. return self.operation(",", other, fn="Math.pow")
  608. def __rpow__(self, other: Var) -> Var:
  609. """Raise a var to a power.
  610. Args:
  611. other: The power to raise to.
  612. Returns:
  613. A var representing the power.
  614. """
  615. return self.operation(",", other, flip=True, fn="Math.pow")
  616. def __truediv__(self, other: Var) -> Var:
  617. """Divide two vars.
  618. Args:
  619. other: The other var to divide.
  620. Returns:
  621. A var representing the quotient.
  622. """
  623. return self.operation("/", other)
  624. def __rtruediv__(self, other: Var) -> Var:
  625. """Divide two vars.
  626. Args:
  627. other: The other var to divide.
  628. Returns:
  629. A var representing the quotient.
  630. """
  631. return self.operation("/", other, flip=True)
  632. def __floordiv__(self, other: Var) -> Var:
  633. """Divide two vars.
  634. Args:
  635. other: The other var to divide.
  636. Returns:
  637. A var representing the quotient.
  638. """
  639. return self.operation("/", other, fn="Math.floor")
  640. def __mod__(self, other: Var) -> Var:
  641. """Get the remainder of two vars.
  642. Args:
  643. other: The other var to divide.
  644. Returns:
  645. A var representing the remainder.
  646. """
  647. return self.operation("%", other)
  648. def __rmod__(self, other: Var) -> Var:
  649. """Get the remainder of two vars.
  650. Args:
  651. other: The other var to divide.
  652. Returns:
  653. A var representing the remainder.
  654. """
  655. return self.operation("%", other, flip=True)
  656. def __and__(self, other: Var) -> Var:
  657. """Perform a logical and.
  658. Args:
  659. other: The other var to perform the logical AND with.
  660. Returns:
  661. A var representing the logical AND.
  662. Note:
  663. This method provides behavior specific to JavaScript, where it returns the JavaScript
  664. equivalent code (using the '&&' operator) of a logical AND operation.
  665. In JavaScript, the
  666. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  667. by returning the equivalent code as a Var instance.
  668. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  669. it challenging to override the behavior entirely.
  670. Therefore, this method leverages the
  671. bitwise AND '__and__' operator for custom JavaScript-like behavior.
  672. Example:
  673. >>> var1 = Var.create(True)
  674. >>> var2 = Var.create(False)
  675. >>> js_code = var1 & var2
  676. >>> print(js_code.full_name)
  677. '(true && false)'
  678. """
  679. return self.operation("&&", other, type_=bool)
  680. def __rand__(self, other: Var) -> Var:
  681. """Perform a logical and.
  682. Args:
  683. other: The other var to perform the logical AND with.
  684. Returns:
  685. A var representing the logical AND.
  686. Note:
  687. This method provides behavior specific to JavaScript, where it returns the JavaScript
  688. equivalent code (using the '&&' operator) of a logical AND operation.
  689. In JavaScript, the
  690. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  691. by returning the equivalent code as a Var instance.
  692. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  693. it challenging to override the behavior entirely.
  694. Therefore, this method leverages the
  695. bitwise AND '__rand__' operator for custom JavaScript-like behavior.
  696. Example:
  697. >>> var1 = Var.create(True)
  698. >>> var2 = Var.create(False)
  699. >>> js_code = var1 & var2
  700. >>> print(js_code.full_name)
  701. '(false && true)'
  702. """
  703. return self.operation("&&", other, type_=bool, flip=True)
  704. def __or__(self, other: Var) -> Var:
  705. """Perform a logical or.
  706. Args:
  707. other: The other var to perform the logical or with.
  708. Returns:
  709. A var representing the logical or.
  710. Note:
  711. This method provides behavior specific to JavaScript, where it returns the JavaScript
  712. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  713. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  714. by returning the equivalent code as a Var instance.
  715. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  716. it challenging to override the behavior entirely. Therefore, this method leverages the
  717. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  718. Example:
  719. >>> var1 = Var.create(True)
  720. >>> var2 = Var.create(False)
  721. >>> js_code = var1 | var2
  722. >>> print(js_code.full_name)
  723. '(true || false)'
  724. """
  725. return self.operation("||", other, type_=bool)
  726. def __ror__(self, other: Var) -> Var:
  727. """Perform a logical or.
  728. Args:
  729. other: The other var to perform the logical or with.
  730. Returns:
  731. A var representing the logical or.
  732. Note:
  733. This method provides behavior specific to JavaScript, where it returns the JavaScript
  734. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  735. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  736. by returning the equivalent code as a Var instance.
  737. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  738. it challenging to override the behavior entirely. Therefore, this method leverages the
  739. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  740. Example:
  741. >>> var1 = Var.create(True)
  742. >>> var2 = Var.create(False)
  743. >>> js_code = var1 | var2
  744. >>> print(js_code)
  745. 'false || true'
  746. """
  747. return self.operation("||", other, type_=bool, flip=True)
  748. def __contains__(self, _: Any) -> Var:
  749. """Override the 'in' operator to alert the user that it is not supported.
  750. Raises:
  751. TypeError: the operation is not supported
  752. """
  753. raise TypeError(
  754. "'in' operator not supported for Var types, use Var.contains() instead."
  755. )
  756. def contains(self, other: Any) -> Var:
  757. """Check if a var contains the object `other`.
  758. Args:
  759. other: The object to check.
  760. Raises:
  761. TypeError: If the var is not a valid type: dict, list, tuple or str.
  762. Returns:
  763. A var representing the contain check.
  764. """
  765. if not (types._issubclass(self.type_, Union[dict, list, tuple, str])):
  766. raise TypeError(
  767. f"Var {self.full_name} of type {self.type_} does not support contains check."
  768. )
  769. method = (
  770. "hasOwnProperty" if types.get_base_class(self.type_) == dict else "includes"
  771. )
  772. if isinstance(other, str):
  773. other = Var.create(json.dumps(other), is_string=True)
  774. elif not isinstance(other, Var):
  775. other = Var.create(other)
  776. if types._issubclass(self.type_, Dict):
  777. return BaseVar(
  778. name=f"{self.full_name}.{method}({other.full_name})",
  779. type_=bool,
  780. is_local=self.is_local,
  781. )
  782. else: # str, list, tuple
  783. # For strings, the left operand must be a string.
  784. if types._issubclass(self.type_, str) and not types._issubclass(
  785. other.type_, str
  786. ):
  787. raise TypeError(
  788. f"'in <string>' requires string as left operand, not {other.type_}"
  789. )
  790. return BaseVar(
  791. name=f"{self.full_name}.includes({other.full_name})",
  792. type_=bool,
  793. is_local=self.is_local,
  794. )
  795. def reverse(self) -> Var:
  796. """Reverse a list var.
  797. Raises:
  798. TypeError: If the var is not a list.
  799. Returns:
  800. A var with the reversed list.
  801. """
  802. if not types._issubclass(self.type_, list):
  803. raise TypeError(f"Cannot reverse non-list var {self.full_name}.")
  804. return BaseVar(
  805. name=f"[...{self.full_name}].reverse()",
  806. type_=self.type_,
  807. is_local=self.is_local,
  808. )
  809. def lower(self) -> Var:
  810. """Convert a string var to lowercase.
  811. Returns:
  812. A var with the lowercase string.
  813. Raises:
  814. TypeError: If the var is not a string.
  815. """
  816. if not types._issubclass(self.type_, str):
  817. raise TypeError(
  818. f"Cannot convert non-string var {self.full_name} to lowercase."
  819. )
  820. return BaseVar(
  821. name=f"{self.full_name}.toLowerCase()",
  822. type_=str,
  823. is_local=self.is_local,
  824. )
  825. def upper(self) -> Var:
  826. """Convert a string var to uppercase.
  827. Returns:
  828. A var with the uppercase string.
  829. Raises:
  830. TypeError: If the var is not a string.
  831. """
  832. if not types._issubclass(self.type_, str):
  833. raise TypeError(
  834. f"Cannot convert non-string var {self.full_name} to uppercase."
  835. )
  836. return BaseVar(
  837. name=f"{self.full_name}.toUpperCase()",
  838. type_=str,
  839. is_local=self.is_local,
  840. )
  841. def split(self, other: str | Var[str] = " ") -> Var:
  842. """Split a string var into a list.
  843. Args:
  844. other: The string to split the var with.
  845. Returns:
  846. A var with the list.
  847. Raises:
  848. TypeError: If the var is not a string.
  849. """
  850. if not types._issubclass(self.type_, str):
  851. raise TypeError(f"Cannot split non-string var {self.full_name}.")
  852. other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
  853. return BaseVar(
  854. name=f"{self.full_name}.split({other.full_name})",
  855. type_=list[str],
  856. is_local=self.is_local,
  857. )
  858. def join(self, other: str | Var[str] | None = None) -> Var:
  859. """Join a list var into a string.
  860. Args:
  861. other: The string to join the list with.
  862. Returns:
  863. A var with the string.
  864. Raises:
  865. TypeError: If the var is not a list.
  866. """
  867. if not types._issubclass(self.type_, list):
  868. raise TypeError(f"Cannot join non-list var {self.full_name}.")
  869. if other is None:
  870. other = Var.create_safe("")
  871. if isinstance(other, str):
  872. other = Var.create_safe(json.dumps(other))
  873. else:
  874. other = Var.create_safe(other)
  875. return BaseVar(
  876. name=f"{self.full_name}.join({other.full_name})",
  877. type_=str,
  878. is_local=self.is_local,
  879. )
  880. def foreach(self, fn: Callable) -> Var:
  881. """Return a list of components. after doing a foreach on this var.
  882. Args:
  883. fn: The function to call on each component.
  884. Returns:
  885. A var representing foreach operation.
  886. """
  887. arg = BaseVar(
  888. name=get_unique_variable_name(),
  889. type_=self.type_,
  890. )
  891. return BaseVar(
  892. name=f"{self.full_name}.map(({arg.name}, i) => {fn(arg, key='i')})",
  893. type_=self.type_,
  894. is_local=self.is_local,
  895. )
  896. def to(self, type_: Type) -> Var:
  897. """Convert the type of the var.
  898. Args:
  899. type_: The type to convert to.
  900. Returns:
  901. The converted var.
  902. """
  903. return BaseVar(
  904. name=self.name,
  905. type_=type_,
  906. state=self.state,
  907. is_local=self.is_local,
  908. )
  909. @property
  910. def full_name(self) -> str:
  911. """Get the full name of the var.
  912. Returns:
  913. The full name of the var.
  914. """
  915. return self.name if self.state == "" else ".".join([self.state, self.name])
  916. def set_state(self, state: Type[State]) -> Any:
  917. """Set the state of the var.
  918. Args:
  919. state: The state to set.
  920. Returns:
  921. The var with the set state.
  922. """
  923. self.state = state.get_full_name()
  924. return self
  925. class BaseVar(Var, Base):
  926. """A base (non-computed) var of the app state."""
  927. # The name of the var.
  928. name: str
  929. # The type of the var.
  930. type_: Any
  931. # The name of the enclosing state.
  932. state: str = ""
  933. # Whether this is a local javascript variable.
  934. is_local: bool = False
  935. # Whether this var is a raw string.
  936. is_string: bool = False
  937. def __hash__(self) -> int:
  938. """Define a hash function for a var.
  939. Returns:
  940. The hash of the var.
  941. """
  942. return hash((self.name, str(self.type_)))
  943. def get_default_value(self) -> Any:
  944. """Get the default value of the var.
  945. Returns:
  946. The default value of the var.
  947. Raises:
  948. ImportError: If the var is a dataframe and pandas is not installed.
  949. """
  950. type_ = (
  951. self.type_.__origin__ if types.is_generic_alias(self.type_) else self.type_
  952. )
  953. if issubclass(type_, str):
  954. return ""
  955. if issubclass(type_, types.get_args(Union[int, float])):
  956. return 0
  957. if issubclass(type_, bool):
  958. return False
  959. if issubclass(type_, list):
  960. return []
  961. if issubclass(type_, dict):
  962. return {}
  963. if issubclass(type_, tuple):
  964. return ()
  965. if types.is_dataframe(type_):
  966. try:
  967. import pandas as pd
  968. return pd.DataFrame()
  969. except ImportError as e:
  970. raise ImportError(
  971. "Please install pandas to use dataframes in your app."
  972. ) from e
  973. return set() if issubclass(type_, set) else None
  974. def get_setter_name(self, include_state: bool = True) -> str:
  975. """Get the name of the var's generated setter function.
  976. Args:
  977. include_state: Whether to include the state name in the setter name.
  978. Returns:
  979. The name of the setter function.
  980. """
  981. setter = constants.SETTER_PREFIX + self.name
  982. if not include_state or self.state == "":
  983. return setter
  984. return ".".join((self.state, setter))
  985. def get_setter(self) -> Callable[[State, Any], None]:
  986. """Get the var's setter function.
  987. Returns:
  988. A function that that creates a setter for the var.
  989. """
  990. def setter(state: State, value: Any):
  991. """Get the setter for the var.
  992. Args:
  993. state: The state within which we add the setter function.
  994. value: The value to set.
  995. """
  996. if self.type_ in [int, float]:
  997. try:
  998. value = self.type_(value)
  999. setattr(state, self.name, value)
  1000. except ValueError:
  1001. console.warn(
  1002. f"{self.name}: Failed conversion of {value} to '{self.type_.__name__}'. Value not set.",
  1003. )
  1004. else:
  1005. setattr(state, self.name, value)
  1006. setter.__qualname__ = self.get_setter_name()
  1007. return setter
  1008. class ComputedVar(Var, property):
  1009. """A field with computed getters."""
  1010. # Whether to track dependencies and cache computed values
  1011. cache: bool = False
  1012. @property
  1013. def name(self) -> str:
  1014. """Get the name of the var.
  1015. Returns:
  1016. The name of the var.
  1017. """
  1018. assert self.fget is not None, "Var must have a getter."
  1019. return self.fget.__name__
  1020. @property
  1021. def cache_attr(self) -> str:
  1022. """Get the attribute used to cache the value on the instance.
  1023. Returns:
  1024. An attribute name.
  1025. """
  1026. return f"__cached_{self.name}"
  1027. def __get__(self, instance, owner):
  1028. """Get the ComputedVar value.
  1029. If the value is already cached on the instance, return the cached value.
  1030. Args:
  1031. instance: the instance of the class accessing this computed var.
  1032. owner: the class that this descriptor is attached to.
  1033. Returns:
  1034. The value of the var for the given instance.
  1035. """
  1036. if instance is None or not self.cache:
  1037. return super().__get__(instance, owner)
  1038. # handle caching
  1039. if not hasattr(instance, self.cache_attr):
  1040. setattr(instance, self.cache_attr, super().__get__(instance, owner))
  1041. return getattr(instance, self.cache_attr)
  1042. def deps(
  1043. self,
  1044. objclass: Type,
  1045. obj: FunctionType | CodeType | None = None,
  1046. self_name: Optional[str] = None,
  1047. ) -> set[str]:
  1048. """Determine var dependencies of this ComputedVar.
  1049. Save references to attributes accessed on "self". Recursively called
  1050. when the function makes a method call on "self" or define comprehensions
  1051. or nested functions that may reference "self".
  1052. Args:
  1053. objclass: the class obj this ComputedVar is attached to.
  1054. obj: the object to disassemble (defaults to the fget function).
  1055. self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
  1056. Returns:
  1057. A set of variable names accessed by the given obj.
  1058. """
  1059. d = set()
  1060. if obj is None:
  1061. if self.fget is not None:
  1062. obj = cast(FunctionType, self.fget)
  1063. else:
  1064. return set()
  1065. with contextlib.suppress(AttributeError):
  1066. # unbox functools.partial
  1067. obj = cast(FunctionType, obj.func) # type: ignore
  1068. with contextlib.suppress(AttributeError):
  1069. # unbox EventHandler
  1070. obj = cast(FunctionType, obj.fn) # type: ignore
  1071. if self_name is None and isinstance(obj, FunctionType):
  1072. try:
  1073. # the first argument to the function is the name of "self" arg
  1074. self_name = obj.__code__.co_varnames[0]
  1075. except (AttributeError, IndexError):
  1076. self_name = None
  1077. if self_name is None:
  1078. # cannot reference attributes on self if method takes no args
  1079. return set()
  1080. self_is_top_of_stack = False
  1081. for instruction in dis.get_instructions(obj):
  1082. if (
  1083. instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
  1084. and instruction.argval == self_name
  1085. ):
  1086. # bytecode loaded the class instance to the top of stack, next load instruction
  1087. # is referencing an attribute on self
  1088. self_is_top_of_stack = True
  1089. continue
  1090. if self_is_top_of_stack and instruction.opname == "LOAD_ATTR":
  1091. # direct attribute access
  1092. d.add(instruction.argval)
  1093. elif self_is_top_of_stack and instruction.opname == "LOAD_METHOD":
  1094. # method call on self
  1095. d.update(
  1096. self.deps(
  1097. objclass=objclass,
  1098. obj=getattr(objclass, instruction.argval),
  1099. )
  1100. )
  1101. elif instruction.opname == "LOAD_CONST" and isinstance(
  1102. instruction.argval, CodeType
  1103. ):
  1104. # recurse into nested functions / comprehensions, which can reference
  1105. # instance attributes from the outer scope
  1106. d.update(
  1107. self.deps(
  1108. objclass=objclass,
  1109. obj=instruction.argval,
  1110. self_name=self_name,
  1111. )
  1112. )
  1113. self_is_top_of_stack = False
  1114. return d
  1115. def mark_dirty(self, instance) -> None:
  1116. """Mark this ComputedVar as dirty.
  1117. Args:
  1118. instance: the state instance that needs to recompute the value.
  1119. """
  1120. with contextlib.suppress(AttributeError):
  1121. delattr(instance, self.cache_attr)
  1122. @property
  1123. def type_(self):
  1124. """Get the type of the var.
  1125. Returns:
  1126. The type of the var.
  1127. """
  1128. hints = get_type_hints(self.fget)
  1129. if "return" in hints:
  1130. return hints["return"]
  1131. return Any
  1132. def cached_var(fget: Callable[[Any], Any]) -> ComputedVar:
  1133. """A field with computed getter that tracks other state dependencies.
  1134. The cached_var will only be recalculated when other state vars that it
  1135. depends on are modified.
  1136. Args:
  1137. fget: the function that calculates the variable value.
  1138. Returns:
  1139. ComputedVar that is recomputed when dependencies change.
  1140. """
  1141. cvar = ComputedVar(fget=fget)
  1142. cvar.cache = True
  1143. return cvar
  1144. class ImportVar(Base):
  1145. """An import var."""
  1146. # The name of the import tag.
  1147. tag: Optional[str]
  1148. # whether the import is default or named.
  1149. is_default: Optional[bool] = False
  1150. # The tag alias.
  1151. alias: Optional[str] = None
  1152. # Whether this import need to install the associated lib
  1153. install: Optional[bool] = True
  1154. # whether this import should be rendered or not
  1155. render: Optional[bool] = True
  1156. @property
  1157. def name(self) -> str:
  1158. """The name of the import.
  1159. Returns:
  1160. The name(tag name with alias) of tag.
  1161. """
  1162. return self.tag if not self.alias else " as ".join([self.tag, self.alias]) # type: ignore
  1163. def __hash__(self) -> int:
  1164. """Define a hash function for the import var.
  1165. Returns:
  1166. The hash of the var.
  1167. """
  1168. return hash((self.tag, self.is_default, self.alias, self.install, self.render))
  1169. class NoRenderImportVar(ImportVar):
  1170. """A import that doesn't need to be rendered."""
  1171. render: Optional[bool] = False
  1172. def get_local_storage(key: Var | str | None = None) -> BaseVar:
  1173. """Provide a base var as payload to get local storage item(s).
  1174. Args:
  1175. key: Key to obtain value in the local storage.
  1176. Returns:
  1177. A BaseVar of the local storage method/function to call.
  1178. Raises:
  1179. TypeError: if the wrong key type is provided.
  1180. """
  1181. if key is not None:
  1182. if not (isinstance(key, Var) and key.type_ == str) and not isinstance(key, str):
  1183. type_ = type(key) if not isinstance(key, Var) else key.type_
  1184. raise TypeError(
  1185. f"Local storage keys can only be of type `str` or `var` of type `str`. Got `{type_}` instead."
  1186. )
  1187. key = key.full_name if isinstance(key, Var) else format.wrap(key, "'")
  1188. return BaseVar(name=f"localStorage.getItem({key})", type_=str)
  1189. return BaseVar(name="getAllLocalStorageItems()", type_=Dict)