var.py 18 KB

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