vars.py 47 KB

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