var.py 21 KB

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