vars.py 49 KB

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