vars.py 39 KB

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