var.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. """Define a state var."""
  2. from __future__ import annotations
  3. import json
  4. from abc import ABC
  5. from typing import _GenericAlias # type: ignore
  6. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union
  7. from plotly.graph_objects import Figure
  8. from plotly.io import to_json
  9. from pydantic.fields import ModelField
  10. from pynecone import constants, utils
  11. from pynecone.base import Base
  12. if TYPE_CHECKING:
  13. from pynecone.state import State
  14. class Var(ABC):
  15. """An abstract var."""
  16. # The name of the var.
  17. name: str
  18. # The type of the var.
  19. type_: Type
  20. # The name of the enclosing state.
  21. state: str = ""
  22. # Whether this is a local javascript variable.
  23. is_local: bool = False
  24. # Whether the var is a string literal.
  25. is_string: bool = False
  26. @classmethod
  27. def create(
  28. cls, value: Any, is_local: bool = True, is_string: bool = False
  29. ) -> Optional[Var]:
  30. """Create a var from a value.
  31. Args:
  32. value: The value to create the var from.
  33. is_local: Whether the var is local.
  34. is_string: Whether the var is a string literal.
  35. Returns:
  36. The var.
  37. """
  38. # Check for none values.
  39. if value is None:
  40. return None
  41. # If the value is already a var, do nothing.
  42. if isinstance(value, Var):
  43. return value
  44. type_ = type(value)
  45. # Special case for plotly figures.
  46. if isinstance(value, Figure):
  47. value = json.loads(to_json(value))["data"]
  48. type_ = Figure
  49. name = json.dumps(value) if not isinstance(value, str) else value
  50. return BaseVar(name=name, type_=type_, is_local=is_local, is_string=is_string)
  51. @classmethod
  52. def __class_getitem__(cls, type_: str) -> _GenericAlias:
  53. """Get a typed var.
  54. Args:
  55. type_: The type of the var.
  56. Returns:
  57. The var class item.
  58. """
  59. return _GenericAlias(cls, type_)
  60. def equals(self, other: Var) -> bool:
  61. """Check if two vars are equal.
  62. Args:
  63. other: The other var to compare.
  64. Returns:
  65. Whether the vars are equal.
  66. """
  67. return (
  68. self.name == other.name
  69. and self.type_ == other.type_
  70. and self.state == other.state
  71. and self.is_local == other.is_local
  72. )
  73. def to_string(self) -> Var:
  74. """Convert a var to a string.
  75. Returns:
  76. The stringified var.
  77. """
  78. return self.operation(fn="JSON.stringify")
  79. def __hash__(self) -> int:
  80. """Define a hash function for a var.
  81. Returns:
  82. The hash of the var.
  83. """
  84. return hash((self.name, str(self.type_)))
  85. def __str__(self) -> str:
  86. """Wrap the var so it can be used in templates.
  87. Returns:
  88. The wrapped var, i.e. {state.var}.
  89. """
  90. if self.is_local:
  91. out = self.full_name
  92. else:
  93. out = utils.wrap(self.full_name, "{")
  94. if self.is_string:
  95. out = utils.format_string(out)
  96. return out
  97. def __getitem__(self, i: Any) -> Var:
  98. """Index into a var.
  99. Args:
  100. i: The index to index into.
  101. Returns:
  102. The indexed var.
  103. Raises:
  104. TypeError: If the var is not indexable.
  105. """
  106. # Indexing is only supported for lists, dicts, and dataframes.
  107. if not (
  108. utils._issubclass(self.type_, Union[List, Dict])
  109. or utils.is_dataframe(self.type_)
  110. ):
  111. raise TypeError(
  112. f"Var {self.name} of type {self.type_} does not support indexing."
  113. )
  114. # The type of the indexed var.
  115. type_ = Any
  116. # Convert any vars to local vars.
  117. if isinstance(i, Var):
  118. i = BaseVar(name=i.name, type_=i.type_, state=i.state, is_local=True)
  119. # Handle list indexing.
  120. if utils._issubclass(self.type_, List):
  121. # List indices must be ints, slices, or vars.
  122. if not isinstance(i, utils.get_args(Union[int, slice, Var])):
  123. raise TypeError("Index must be an integer.")
  124. # Handle slices first.
  125. if isinstance(i, slice):
  126. # Get the start and stop indices.
  127. start = i.start or 0
  128. stop = i.stop or "undefined"
  129. # Use the slice function.
  130. return BaseVar(
  131. name=f"{self.name}.slice({start}, {stop})",
  132. type_=self.type_,
  133. state=self.state,
  134. )
  135. # Get the type of the indexed var.
  136. if utils.is_generic_alias(self.type_):
  137. type_ = utils.get_args(self.type_)[0]
  138. else:
  139. type_ = Any
  140. # Use `at` to support negative indices.
  141. return BaseVar(
  142. name=f"{self.name}.at({i})",
  143. type_=type_,
  144. state=self.state,
  145. )
  146. # Dictionary / dataframe indexing.
  147. # Get the type of the indexed var.
  148. if isinstance(i, str):
  149. i = utils.wrap(i, '"')
  150. if utils.is_generic_alias(self.type_):
  151. type_ = utils.get_args(self.type_)[1]
  152. else:
  153. type_ = Any
  154. # Use normal indexing here.
  155. return BaseVar(
  156. name=f"{self.name}[{i}]",
  157. type_=type_,
  158. state=self.state,
  159. )
  160. def __getattribute__(self, name: str) -> Var:
  161. """Get a var attribute.
  162. Args:
  163. name: The name of the attribute.
  164. Returns:
  165. The var attribute.
  166. Raises:
  167. Exception: If the attribute is not found.
  168. """
  169. try:
  170. return super().__getattribute__(name)
  171. except Exception as e:
  172. # Check if the attribute is one of the class fields.
  173. if (
  174. not name.startswith("_")
  175. and hasattr(self.type_, "__fields__")
  176. and name in self.type_.__fields__
  177. ):
  178. type_ = self.type_.__fields__[name].outer_type_
  179. if isinstance(type_, ModelField):
  180. type_ = type_.type_
  181. return BaseVar(
  182. name=f"{self.name}.{name}",
  183. type_=type_,
  184. state=self.state,
  185. )
  186. raise e
  187. def operation(
  188. self,
  189. op: str = "",
  190. other: Optional[Var] = None,
  191. type_: Optional[Type] = None,
  192. flip: bool = False,
  193. fn: Optional[str] = None,
  194. ) -> Var:
  195. """Perform an operation on a var.
  196. Args:
  197. op: The operation to perform.
  198. other: The other var to perform the operation on.
  199. type_: The type of the operation result.
  200. flip: Whether to flip the order of the operation.
  201. fn: A function to apply to the operation.
  202. Returns:
  203. The operation result.
  204. """
  205. # Wrap strings in quotes.
  206. if isinstance(other, str):
  207. other = Var.create(json.dumps(other))
  208. else:
  209. other = Var.create(other)
  210. if type_ is None:
  211. type_ = self.type_
  212. if other is None:
  213. name = f"{op}{self.full_name}"
  214. else:
  215. props = (self, other) if not flip else (other, self)
  216. name = f"{props[0].full_name} {op} {props[1].full_name}"
  217. if fn is None:
  218. name = utils.wrap(name, "(")
  219. if fn is not None:
  220. name = f"{fn}({name})"
  221. return BaseVar(
  222. name=name,
  223. type_=type_,
  224. )
  225. def compare(self, op: str, other: Var) -> Var:
  226. """Compare two vars with inequalities.
  227. Args:
  228. op: The comparison operator.
  229. other: The other var to compare with.
  230. Returns:
  231. The comparison result.
  232. """
  233. return self.operation(op, other, bool)
  234. def __invert__(self) -> Var:
  235. """Invert a var.
  236. Returns:
  237. The inverted var.
  238. """
  239. return self.operation("!", type_=bool)
  240. def __neg__(self) -> Var:
  241. """Negate a var.
  242. Returns:
  243. The negated var.
  244. """
  245. return self.operation(fn="-")
  246. def __abs__(self) -> Var:
  247. """Get the absolute value of a var.
  248. Returns:
  249. A var with the absolute value.
  250. """
  251. return self.operation(fn="Math.abs")
  252. def length(self) -> Var:
  253. """Get the length of a list var.
  254. Returns:
  255. A var with the absolute value.
  256. Raises:
  257. TypeError: If the var is not a list.
  258. """
  259. if not utils._issubclass(self.type_, List):
  260. raise TypeError(f"Cannot get length of non-list var {self}.")
  261. return BaseVar(
  262. name=f"{self.full_name}.length",
  263. type_=int,
  264. )
  265. def __eq__(self, other: Var) -> Var:
  266. """Perform an equality comparison.
  267. Args:
  268. other: The other var to compare with.
  269. Returns:
  270. A var representing the equality comparison.
  271. """
  272. return self.compare("==", other)
  273. def __ne__(self, other: Var) -> Var:
  274. """Perform an inequality comparison.
  275. Args:
  276. other: The other var to compare with.
  277. Returns:
  278. A var representing the inequality comparison.
  279. """
  280. return self.compare("!=", other)
  281. def __gt__(self, other: Var) -> Var:
  282. """Perform a greater than comparison.
  283. Args:
  284. other: The other var to compare with.
  285. Returns:
  286. A var representing the greater than comparison.
  287. """
  288. return self.compare(">", other)
  289. def __ge__(self, other: Var) -> Var:
  290. """Perform a greater than or equal to comparison.
  291. Args:
  292. other: The other var to compare with.
  293. Returns:
  294. A var representing the greater than or equal to comparison.
  295. """
  296. return self.compare(">=", other)
  297. def __lt__(self, other: Var) -> Var:
  298. """Perform a less than comparison.
  299. Args:
  300. other: The other var to compare with.
  301. Returns:
  302. A var representing the less than comparison.
  303. """
  304. return self.compare("<", other)
  305. def __le__(self, other: Var) -> Var:
  306. """Perform a less than or equal to comparison.
  307. Args:
  308. other: The other var to compare with.
  309. Returns:
  310. A var representing the less than or equal to comparison.
  311. """
  312. return self.compare("<=", other)
  313. def __add__(self, other: Var) -> Var:
  314. """Add two vars.
  315. Args:
  316. other: The other var to add.
  317. Returns:
  318. A var representing the sum.
  319. """
  320. return self.operation("+", other)
  321. def __radd__(self, other: Var) -> Var:
  322. """Add two vars.
  323. Args:
  324. other: The other var to add.
  325. Returns:
  326. A var representing the sum.
  327. """
  328. return self.operation("+", other, flip=True)
  329. def __sub__(self, other: Var) -> Var:
  330. """Subtract two vars.
  331. Args:
  332. other: The other var to subtract.
  333. Returns:
  334. A var representing the difference.
  335. """
  336. return self.operation("-", other)
  337. def __rsub__(self, other: Var) -> Var:
  338. """Subtract two vars.
  339. Args:
  340. other: The other var to subtract.
  341. Returns:
  342. A var representing the difference.
  343. """
  344. return self.operation("-", other, flip=True)
  345. def __mul__(self, other: Var) -> Var:
  346. """Multiply two vars.
  347. Args:
  348. other: The other var to multiply.
  349. Returns:
  350. A var representing the product.
  351. """
  352. return self.operation("*", other)
  353. def __rmul__(self, other: Var) -> Var:
  354. """Multiply two vars.
  355. Args:
  356. other: The other var to multiply.
  357. Returns:
  358. A var representing the product.
  359. """
  360. return self.operation("*", other, flip=True)
  361. def __pow__(self, other: Var) -> Var:
  362. """Raise a var to a power.
  363. Args:
  364. other: The power to raise to.
  365. Returns:
  366. A var representing the power.
  367. """
  368. return self.operation(",", other, fn="Math.pow")
  369. def __rpow__(self, other: Var) -> Var:
  370. """Raise a var to a power.
  371. Args:
  372. other: The power to raise to.
  373. Returns:
  374. A var representing the power.
  375. """
  376. return self.operation(",", other, flip=True, fn="Math.pow")
  377. def __truediv__(self, other: Var) -> Var:
  378. """Divide two vars.
  379. Args:
  380. other: The other var to divide.
  381. Returns:
  382. A var representing the quotient.
  383. """
  384. return self.operation("/", other)
  385. def __rtruediv__(self, other: Var) -> Var:
  386. """Divide two vars.
  387. Args:
  388. other: The other var to divide.
  389. Returns:
  390. A var representing the quotient.
  391. """
  392. return self.operation("/", other, flip=True)
  393. def __floordiv__(self, other: Var) -> Var:
  394. """Divide two vars.
  395. Args:
  396. other: The other var to divide.
  397. Returns:
  398. A var representing the quotient.
  399. """
  400. return self.operation("/", other, fn="Math.floor")
  401. def __mod__(self, other: Var) -> Var:
  402. """Get the remainder of two vars.
  403. Args:
  404. other: The other var to divide.
  405. Returns:
  406. A var representing the remainder.
  407. """
  408. return self.operation("%", other)
  409. def __rmod__(self, other: Var) -> Var:
  410. """Get the remainder of two vars.
  411. Args:
  412. other: The other var to divide.
  413. Returns:
  414. A var representing the remainder.
  415. """
  416. return self.operation("%", other, flip=True)
  417. def __and__(self, other: Var) -> Var:
  418. """Perform a logical and.
  419. Args:
  420. other: The other var to perform the logical and with.
  421. Returns:
  422. A var representing the logical and.
  423. """
  424. return self.operation("&&", other)
  425. def __rand__(self, other: Var) -> Var:
  426. """Perform a logical and.
  427. Args:
  428. other: The other var to perform the logical and with.
  429. Returns:
  430. A var representing the logical and.
  431. """
  432. return self.operation("&&", other, flip=True)
  433. def __or__(self, other: Var) -> Var:
  434. """Perform a logical or.
  435. Args:
  436. other: The other var to perform the logical or with.
  437. Returns:
  438. A var representing the logical or.
  439. """
  440. return self.operation("||", other)
  441. def __ror__(self, other: Var) -> Var:
  442. """Perform a logical or.
  443. Args:
  444. other: The other var to perform the logical or with.
  445. Returns:
  446. A var representing the logical or.
  447. """
  448. return self.operation("||", other, flip=True)
  449. def foreach(self, fn: Callable) -> Var:
  450. """Return a list of components. after doing a foreach on this var.
  451. Args:
  452. fn: The function to call on each component.
  453. Returns:
  454. A var representing foreach operation.
  455. """
  456. arg = BaseVar(
  457. name=utils.get_unique_variable_name(),
  458. type_=self.type_,
  459. )
  460. return BaseVar(
  461. name=f"{self.full_name}.map(({arg.name}, i) => {fn(arg, key='i')})",
  462. type_=self.type_,
  463. )
  464. def to(self, type_: Type) -> Var:
  465. """Convert the type of the var.
  466. Args:
  467. type_: The type to convert to.
  468. Returns:
  469. The converted var.
  470. """
  471. return BaseVar(
  472. name=self.name,
  473. type_=type_,
  474. state=self.state,
  475. is_local=self.is_local,
  476. )
  477. @property
  478. def full_name(self) -> str:
  479. """Get the full name of the var.
  480. Returns:
  481. The full name of the var.
  482. """
  483. if self.state == "":
  484. return self.name
  485. return ".".join([self.state, self.name])
  486. def set_state(self, state: Type[State]) -> Any:
  487. """Set the state of the var.
  488. Args:
  489. state: The state to set.
  490. Returns:
  491. The var with the set state.
  492. """
  493. self.state = state.get_full_name()
  494. return self
  495. class BaseVar(Var, Base):
  496. """A base (non-computed) var of the app state."""
  497. # The name of the var.
  498. name: str
  499. # The type of the var.
  500. type_: Any
  501. # The name of the enclosing state.
  502. state: str = ""
  503. # Whether this is a local javascript variable.
  504. is_local: bool = False
  505. # Whether this var is a raw string.
  506. is_string: bool = False
  507. def __hash__(self) -> int:
  508. """Define a hash function for a var.
  509. Returns:
  510. The hash of the var.
  511. """
  512. return hash((self.name, str(self.type_)))
  513. def get_default_value(self) -> Any:
  514. """Get the default value of the var.
  515. Returns:
  516. The default value of the var.
  517. """
  518. if utils.is_generic_alias(self.type_):
  519. type_ = self.type_.__origin__
  520. else:
  521. type_ = self.type_
  522. if issubclass(type_, str):
  523. return ""
  524. if issubclass(type_, utils.get_args(Union[int, float])):
  525. return 0
  526. if issubclass(type_, bool):
  527. return False
  528. if issubclass(type_, list):
  529. return []
  530. if issubclass(type_, dict):
  531. return {}
  532. if issubclass(type_, tuple):
  533. return ()
  534. if issubclass(type_, set):
  535. return set()
  536. return None
  537. def get_setter_name(self, include_state: bool = True) -> str:
  538. """Get the name of the var's generated setter function.
  539. Args:
  540. include_state: Whether to include the state name in the setter name.
  541. Returns:
  542. The name of the setter function.
  543. """
  544. setter = constants.SETTER_PREFIX + self.name
  545. if not include_state or self.state == "":
  546. return setter
  547. return ".".join((self.state, setter))
  548. def get_setter(self) -> Callable[[State, Any], None]:
  549. """Get the var's setter function.
  550. Returns:
  551. A function that that creates a setter for the var.
  552. """
  553. def setter(state: State, value: Any):
  554. """Get the setter for the var.
  555. Args:
  556. state: The state within which we add the setter function.
  557. value: The value to set.
  558. """
  559. setattr(state, self.name, value)
  560. setter.__qualname__ = self.get_setter_name()
  561. return setter
  562. def json(self) -> str:
  563. """Convert the object to a json string.
  564. Returns:
  565. The object as a json string.
  566. """
  567. return self.__config__.json_dumps(self.dict())
  568. class ComputedVar(property, Var):
  569. """A field with computed getters."""
  570. @property
  571. def name(self) -> str:
  572. """Get the name of the var.
  573. Returns:
  574. The name of the var.
  575. """
  576. assert self.fget is not None, "Var must have a getter."
  577. return self.fget.__name__
  578. @property
  579. def type_(self):
  580. """Get the type of the var.
  581. Returns:
  582. The type of the var.
  583. """
  584. if "return" in self.fget.__annotations__:
  585. return self.fget.__annotations__["return"]
  586. return Any