var.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. # The type of the indexed var.
  107. type_ = str
  108. # Convert any vars to local vars.
  109. if isinstance(i, Var):
  110. i = BaseVar(name=i.name, type_=i.type_, state=i.state, is_local=True)
  111. if utils._issubclass(self.type_, List):
  112. assert isinstance(
  113. i, utils.get_args(Union[int, Var])
  114. ), "Index must be an integer."
  115. if utils.is_generic_alias(self.type_):
  116. type_ = utils.get_args(self.type_)[0]
  117. else:
  118. type_ = Any
  119. elif utils._issubclass(self.type_, Dict) or utils.is_dataframe(self.type_):
  120. if isinstance(i, str):
  121. i = utils.wrap(i, '"')
  122. if utils.is_generic_alias(self.type_):
  123. type_ = utils.get_args(self.type_)[1]
  124. else:
  125. type_ = Any
  126. else:
  127. raise TypeError(
  128. f"Var {self.name} of type {self.type_} does not support indexing."
  129. )
  130. return BaseVar(
  131. name=f"{self.name}[{i}]",
  132. type_=type_,
  133. state=self.state,
  134. )
  135. def __getattribute__(self, name: str) -> Var:
  136. """Get a var attribute.
  137. Args:
  138. name: The name of the attribute.
  139. Returns:
  140. The var attribute.
  141. Raises:
  142. Exception: If the attribute is not found.
  143. """
  144. try:
  145. return super().__getattribute__(name)
  146. except Exception as e:
  147. # Check if the attribute is one of the class fields.
  148. if (
  149. not name.startswith("_")
  150. and hasattr(self.type_, "__fields__")
  151. and name in self.type_.__fields__
  152. ):
  153. type_ = self.type_.__fields__[name].outer_type_
  154. if isinstance(type_, ModelField):
  155. type_ = type_.type_
  156. return BaseVar(
  157. name=f"{self.name}.{name}",
  158. type_=type_,
  159. state=self.state,
  160. )
  161. raise e
  162. def operation(
  163. self,
  164. op: str = "",
  165. other: Optional[Var] = None,
  166. type_: Optional[Type] = None,
  167. flip: bool = False,
  168. fn: Optional[str] = None,
  169. ) -> Var:
  170. """Perform an operation on a var.
  171. Args:
  172. op: The operation to perform.
  173. other: The other var to perform the operation on.
  174. type_: The type of the operation result.
  175. flip: Whether to flip the order of the operation.
  176. fn: A function to apply to the operation.
  177. Returns:
  178. The operation result.
  179. """
  180. # Wrap strings in quotes.
  181. if isinstance(other, str):
  182. other = Var.create(json.dumps(other))
  183. else:
  184. other = Var.create(other)
  185. if type_ is None:
  186. type_ = self.type_
  187. if other is None:
  188. name = f"{op}{self.full_name}"
  189. else:
  190. props = (self, other) if not flip else (other, self)
  191. name = f"{props[0].full_name} {op} {props[1].full_name}"
  192. if fn is None:
  193. name = utils.wrap(name, "(")
  194. if fn is not None:
  195. name = f"{fn}({name})"
  196. return BaseVar(
  197. name=name,
  198. type_=type_,
  199. )
  200. def compare(self, op: str, other: Var) -> Var:
  201. """Compare two vars with inequalities.
  202. Args:
  203. op: The comparison operator.
  204. other: The other var to compare with.
  205. Returns:
  206. The comparison result.
  207. """
  208. return self.operation(op, other, bool)
  209. def __invert__(self) -> Var:
  210. """Invert a var.
  211. Returns:
  212. The inverted var.
  213. """
  214. return self.operation("!", type_=bool)
  215. def __neg__(self) -> Var:
  216. """Negate a var.
  217. Returns:
  218. The negated var.
  219. """
  220. return self.operation(fn="-")
  221. def __abs__(self) -> Var:
  222. """Get the absolute value of a var.
  223. Returns:
  224. A var with the absolute value.
  225. """
  226. return self.operation(fn="Math.abs")
  227. def __eq__(self, other: Var) -> Var:
  228. """Perform an equality comparison.
  229. Args:
  230. other: The other var to compare with.
  231. Returns:
  232. A var representing the equality comparison.
  233. """
  234. return self.compare("==", other)
  235. def __ne__(self, other: Var) -> Var:
  236. """Perform an inequality comparison.
  237. Args:
  238. other: The other var to compare with.
  239. Returns:
  240. A var representing the inequality comparison.
  241. """
  242. return self.compare("!=", other)
  243. def __gt__(self, other: Var) -> Var:
  244. """Perform a greater than comparison.
  245. Args:
  246. other: The other var to compare with.
  247. Returns:
  248. A var representing the greater than comparison.
  249. """
  250. return self.compare(">", other)
  251. def __ge__(self, other: Var) -> Var:
  252. """Perform a greater than or equal to comparison.
  253. Args:
  254. other: The other var to compare with.
  255. Returns:
  256. A var representing the greater than or equal to comparison.
  257. """
  258. return self.compare(">=", other)
  259. def __lt__(self, other: Var) -> Var:
  260. """Perform a less than comparison.
  261. Args:
  262. other: The other var to compare with.
  263. Returns:
  264. A var representing the less than comparison.
  265. """
  266. return self.compare("<", other)
  267. def __le__(self, other: Var) -> Var:
  268. """Perform a less than or equal to comparison.
  269. Args:
  270. other: The other var to compare with.
  271. Returns:
  272. A var representing the less than or equal to comparison.
  273. """
  274. return self.compare("<=", other)
  275. def __add__(self, other: Var) -> Var:
  276. """Add two vars.
  277. Args:
  278. other: The other var to add.
  279. Returns:
  280. A var representing the sum.
  281. """
  282. return self.operation("+", other)
  283. def __radd__(self, other: Var) -> Var:
  284. """Add two vars.
  285. Args:
  286. other: The other var to add.
  287. Returns:
  288. A var representing the sum.
  289. """
  290. return self.operation("+", other, flip=True)
  291. def __sub__(self, other: Var) -> Var:
  292. """Subtract two vars.
  293. Args:
  294. other: The other var to subtract.
  295. Returns:
  296. A var representing the difference.
  297. """
  298. return self.operation("-", other)
  299. def __rsub__(self, other: Var) -> Var:
  300. """Subtract two vars.
  301. Args:
  302. other: The other var to subtract.
  303. Returns:
  304. A var representing the difference.
  305. """
  306. return self.operation("-", other, flip=True)
  307. def __mul__(self, other: Var) -> Var:
  308. """Multiply two vars.
  309. Args:
  310. other: The other var to multiply.
  311. Returns:
  312. A var representing the product.
  313. """
  314. return self.operation("*", other)
  315. def __rmul__(self, other: Var) -> Var:
  316. """Multiply two vars.
  317. Args:
  318. other: The other var to multiply.
  319. Returns:
  320. A var representing the product.
  321. """
  322. return self.operation("*", other, flip=True)
  323. def __pow__(self, other: Var) -> Var:
  324. """Raise a var to a power.
  325. Args:
  326. other: The power to raise to.
  327. Returns:
  328. A var representing the power.
  329. """
  330. return self.operation(",", other, fn="Math.pow")
  331. def __rpow__(self, other: Var) -> Var:
  332. """Raise a var to a power.
  333. Args:
  334. other: The power to raise to.
  335. Returns:
  336. A var representing the power.
  337. """
  338. return self.operation(",", other, flip=True, fn="Math.pow")
  339. def __truediv__(self, other: Var) -> Var:
  340. """Divide two vars.
  341. Args:
  342. other: The other var to divide.
  343. Returns:
  344. A var representing the quotient.
  345. """
  346. return self.operation("/", other)
  347. def __rtruediv__(self, other: Var) -> Var:
  348. """Divide two vars.
  349. Args:
  350. other: The other var to divide.
  351. Returns:
  352. A var representing the quotient.
  353. """
  354. return self.operation("/", other, flip=True)
  355. def __floordiv__(self, other: Var) -> Var:
  356. """Divide two vars.
  357. Args:
  358. other: The other var to divide.
  359. Returns:
  360. A var representing the quotient.
  361. """
  362. return self.operation("/", other, fn="Math.floor")
  363. def __mod__(self, other: Var) -> Var:
  364. """Get the remainder of two vars.
  365. Args:
  366. other: The other var to divide.
  367. Returns:
  368. A var representing the remainder.
  369. """
  370. return self.operation("%", other)
  371. def __rmod__(self, other: Var) -> Var:
  372. """Get the remainder of two vars.
  373. Args:
  374. other: The other var to divide.
  375. Returns:
  376. A var representing the remainder.
  377. """
  378. return self.operation("%", other, flip=True)
  379. def __and__(self, other: Var) -> Var:
  380. """Perform a logical and.
  381. Args:
  382. other: The other var to perform the logical and with.
  383. Returns:
  384. A var representing the logical and.
  385. """
  386. return self.operation("&&", other)
  387. def __rand__(self, other: Var) -> Var:
  388. """Perform a logical and.
  389. Args:
  390. other: The other var to perform the logical and with.
  391. Returns:
  392. A var representing the logical and.
  393. """
  394. return self.operation("&&", other, flip=True)
  395. def __or__(self, other: Var) -> Var:
  396. """Perform a logical or.
  397. Args:
  398. other: The other var to perform the logical or with.
  399. Returns:
  400. A var representing the logical or.
  401. """
  402. return self.operation("||", other)
  403. def __ror__(self, other: Var) -> Var:
  404. """Perform a logical or.
  405. Args:
  406. other: The other var to perform the logical or with.
  407. Returns:
  408. A var representing the logical or.
  409. """
  410. return self.operation("||", other, flip=True)
  411. def foreach(self, fn: Callable) -> Var:
  412. """Return a list of components. after doing a foreach on this var.
  413. Args:
  414. fn: The function to call on each component.
  415. Returns:
  416. A var representing foreach operation.
  417. """
  418. arg = BaseVar(
  419. name=utils.get_unique_variable_name(),
  420. type_=self.type_,
  421. )
  422. return BaseVar(
  423. name=f"{self.full_name}.map(({arg.name}, i) => {fn(arg, key='i')})",
  424. type_=self.type_,
  425. )
  426. def to(self, type_: Type) -> Var:
  427. """Convert the type of the var.
  428. Args:
  429. type_: The type to convert to.
  430. Returns:
  431. The converted var.
  432. """
  433. return BaseVar(
  434. name=self.name,
  435. type_=type_,
  436. state=self.state,
  437. is_local=self.is_local,
  438. )
  439. @property
  440. def full_name(self) -> str:
  441. """Get the full name of the var.
  442. Returns:
  443. The full name of the var.
  444. """
  445. if self.state == "":
  446. return self.name
  447. return ".".join([self.state, self.name])
  448. def set_state(self, state: Type[State]) -> Any:
  449. """Set the state of the var.
  450. Args:
  451. state: The state to set.
  452. Returns:
  453. The var with the set state.
  454. """
  455. self.state = state.get_full_name()
  456. return self
  457. class BaseVar(Var, Base):
  458. """A base (non-computed) var of the app state."""
  459. # The name of the var.
  460. name: str
  461. # The type of the var.
  462. type_: Any
  463. # The name of the enclosing state.
  464. state: str = ""
  465. # Whether this is a local javascript variable.
  466. is_local: bool = False
  467. is_string: bool = False
  468. def __hash__(self) -> int:
  469. """Define a hash function for a var.
  470. Returns:
  471. The hash of the var.
  472. """
  473. return hash((self.name, str(self.type_)))
  474. def get_default_value(self) -> Any:
  475. """Get the default value of the var.
  476. Returns:
  477. The default value of the var.
  478. """
  479. if utils.is_generic_alias(self.type_):
  480. type_ = self.type_.__origin__
  481. else:
  482. type_ = self.type_
  483. if issubclass(type_, str):
  484. return ""
  485. if issubclass(type_, utils.get_args(Union[int, float])):
  486. return 0
  487. if issubclass(type_, bool):
  488. return False
  489. if issubclass(type_, list):
  490. return []
  491. if issubclass(type_, dict):
  492. return {}
  493. if issubclass(type_, tuple):
  494. return ()
  495. if issubclass(type_, set):
  496. return set()
  497. return None
  498. def get_setter_name(self, include_state: bool = True) -> str:
  499. """Get the name of the var's generated setter function.
  500. Args:
  501. include_state: Whether to include the state name in the setter name.
  502. Returns:
  503. The name of the setter function.
  504. """
  505. setter = constants.SETTER_PREFIX + self.name
  506. if not include_state or self.state == "":
  507. return setter
  508. return ".".join((self.state, setter))
  509. def get_setter(self) -> Callable[[State, Any], None]:
  510. """Get the var's setter function.
  511. Returns:
  512. A function that that creates a setter for the var.
  513. """
  514. def setter(state: State, value: Any):
  515. """Get the setter for the var.
  516. Args:
  517. state: The state within which we add the setter function.
  518. value: The value to set.
  519. """
  520. setattr(state, self.name, value)
  521. setter.__qualname__ = self.get_setter_name()
  522. return setter
  523. def json(self) -> str:
  524. """Convert the object to a json string.
  525. Returns:
  526. The object as a json string.
  527. """
  528. return self.__config__.json_dumps(self.dict())
  529. class ComputedVar(property, Var):
  530. """A field with computed getters."""
  531. @property
  532. def name(self) -> str:
  533. """Get the name of the var.
  534. Returns:
  535. The name of the var.
  536. """
  537. assert self.fget is not None, "Var must have a getter."
  538. return self.fget.__name__
  539. @property
  540. def type_(self):
  541. """Get the type of the var.
  542. Returns:
  543. The type of the var.
  544. """
  545. if "return" in self.fget.__annotations__:
  546. return self.fget.__annotations__["return"]
  547. return Any