vars.py 46 KB

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