var.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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. Type,
  19. Union,
  20. _GenericAlias, # type: ignore
  21. cast,
  22. get_type_hints,
  23. )
  24. from plotly.graph_objects import Figure
  25. from plotly.io import to_json
  26. from pydantic.fields import ModelField
  27. from pynecone import constants
  28. from pynecone.base import Base
  29. from pynecone.utils import format, types
  30. if TYPE_CHECKING:
  31. from pynecone.state import State
  32. # Set of unique variable names.
  33. USED_VARIABLES = set()
  34. def get_unique_variable_name() -> str:
  35. """Get a unique variable name.
  36. Returns:
  37. The unique variable name.
  38. """
  39. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  40. if name not in USED_VARIABLES:
  41. USED_VARIABLES.add(name)
  42. return name
  43. return get_unique_variable_name()
  44. class Var(ABC):
  45. """An abstract var."""
  46. # The name of the var.
  47. name: str
  48. # The type of the var.
  49. type_: Type
  50. # The name of the enclosing state.
  51. state: str = ""
  52. # Whether this is a local javascript variable.
  53. is_local: bool = False
  54. # Whether the var is a string literal.
  55. is_string: bool = False
  56. @classmethod
  57. def create(
  58. cls, value: Any, is_local: bool = True, is_string: bool = False
  59. ) -> Optional[Var]:
  60. """Create a var from a value.
  61. Args:
  62. value: The value to create the var from.
  63. is_local: Whether the var is local.
  64. is_string: Whether the var is a string literal.
  65. Returns:
  66. The var.
  67. Raises:
  68. TypeError: If the value is JSON-unserializable.
  69. """
  70. # Check for none values.
  71. if value is None:
  72. return None
  73. # If the value is already a var, do nothing.
  74. if isinstance(value, Var):
  75. return value
  76. type_ = type(value)
  77. # Special case for plotly figures.
  78. if isinstance(value, Figure):
  79. value = json.loads(to_json(value))["data"] # type: ignore
  80. type_ = Figure
  81. try:
  82. name = value if isinstance(value, str) else json.dumps(value)
  83. except TypeError as e:
  84. raise TypeError(
  85. f"To create a Var must be Var or JSON-serializable. Got {value} of type {type(value)}."
  86. ) from e
  87. return BaseVar(name=name, type_=type_, is_local=is_local, is_string=is_string)
  88. @classmethod
  89. def create_safe(
  90. cls, value: Any, is_local: bool = True, is_string: bool = False
  91. ) -> Var:
  92. """Create a var from a value, guaranteeing that it is not None.
  93. Args:
  94. value: The value to create the var from.
  95. is_local: Whether the var is local.
  96. is_string: Whether the var is a string literal.
  97. Returns:
  98. The var.
  99. """
  100. var = cls.create(value, is_local=is_local, is_string=is_string)
  101. assert var is not None
  102. return var
  103. @classmethod
  104. def __class_getitem__(cls, type_: str) -> _GenericAlias:
  105. """Get a typed var.
  106. Args:
  107. type_: The type of the var.
  108. Returns:
  109. The var class item.
  110. """
  111. return _GenericAlias(cls, type_)
  112. def equals(self, other: Var) -> bool:
  113. """Check if two vars are equal.
  114. Args:
  115. other: The other var to compare.
  116. Returns:
  117. Whether the vars are equal.
  118. """
  119. return (
  120. self.name == other.name
  121. and self.type_ == other.type_
  122. and self.state == other.state
  123. and self.is_local == other.is_local
  124. )
  125. def to_string(self) -> Var:
  126. """Convert a var to a string.
  127. Returns:
  128. The stringified var.
  129. """
  130. return self.operation(fn="JSON.stringify")
  131. def __hash__(self) -> int:
  132. """Define a hash function for a var.
  133. Returns:
  134. The hash of the var.
  135. """
  136. return hash((self.name, str(self.type_)))
  137. def __str__(self) -> str:
  138. """Wrap the var so it can be used in templates.
  139. Returns:
  140. The wrapped var, i.e. {state.var}.
  141. """
  142. out = self.full_name if self.is_local else format.wrap(self.full_name, "{")
  143. if self.is_string:
  144. out = format.format_string(out)
  145. return out
  146. def __getitem__(self, i: Any) -> Var:
  147. """Index into a var.
  148. Args:
  149. i: The index to index into.
  150. Returns:
  151. The indexed var.
  152. Raises:
  153. TypeError: If the var is not indexable.
  154. """
  155. # Indexing is only supported for lists, dicts, and dataframes.
  156. if not (
  157. types._issubclass(self.type_, Union[List, Dict])
  158. or types.is_dataframe(self.type_)
  159. ):
  160. if self.type_ == Any:
  161. raise TypeError(
  162. f"Could not index into var of type Any. (If you are trying to index into a state var, add a type annotation to the var.)"
  163. )
  164. raise TypeError(
  165. f"Var {self.name} of type {self.type_} does not support indexing."
  166. )
  167. # The type of the indexed var.
  168. type_ = Any
  169. # Convert any vars to local vars.
  170. if isinstance(i, Var):
  171. i = BaseVar(name=i.name, type_=i.type_, state=i.state, is_local=True)
  172. # Handle list indexing.
  173. if types._issubclass(self.type_, List):
  174. # List indices must be ints, slices, or vars.
  175. if not isinstance(i, types.get_args(Union[int, slice, Var])):
  176. raise TypeError("Index must be an integer.")
  177. # Handle slices first.
  178. if isinstance(i, slice):
  179. # Get the start and stop indices.
  180. start = i.start or 0
  181. stop = i.stop or "undefined"
  182. # Use the slice function.
  183. return BaseVar(
  184. name=f"{self.name}.slice({start}, {stop})",
  185. type_=self.type_,
  186. state=self.state,
  187. )
  188. # Get the type of the indexed var.
  189. type_ = (
  190. types.get_args(self.type_)[0]
  191. if types.is_generic_alias(self.type_)
  192. else Any
  193. )
  194. # Use `at` to support negative indices.
  195. return BaseVar(
  196. name=f"{self.name}.at({i})",
  197. type_=type_,
  198. state=self.state,
  199. )
  200. # Dictionary / dataframe indexing.
  201. # Get the type of the indexed var.
  202. if isinstance(i, str):
  203. i = format.wrap(i, '"')
  204. type_ = (
  205. types.get_args(self.type_)[1] if types.is_generic_alias(self.type_) else Any
  206. )
  207. # Use normal indexing here.
  208. return BaseVar(
  209. name=f"{self.name}[{i}]",
  210. type_=type_,
  211. state=self.state,
  212. )
  213. def __getattribute__(self, name: str) -> Var:
  214. """Get a var attribute.
  215. Args:
  216. name: The name of the attribute.
  217. Returns:
  218. The var attribute.
  219. Raises:
  220. AttributeError: If the var is wrongly annotated or can't find attribute.
  221. TypeError: If an annotation to the var isn't provided.
  222. """
  223. try:
  224. return super().__getattribute__(name)
  225. except Exception as e:
  226. # Check if the attribute is one of the class fields.
  227. if not name.startswith("_"):
  228. if self.type_ == Any:
  229. raise TypeError(
  230. f"You must provide an annotation for the state var `{self.full_name}`. Annotation cannot be `{self.type_}`"
  231. ) from None
  232. if hasattr(self.type_, "__fields__") and name in self.type_.__fields__:
  233. type_ = self.type_.__fields__[name].outer_type_
  234. if isinstance(type_, ModelField):
  235. type_ = type_.type_
  236. return BaseVar(
  237. name=f"{self.name}.{name}",
  238. type_=type_,
  239. state=self.state,
  240. )
  241. raise AttributeError(
  242. f"The State var `{self.full_name}` has no attribute '{name}' or may have been annotated "
  243. f"wrongly.\n"
  244. f"original message: {e.args[0]}"
  245. ) from e
  246. def operation(
  247. self,
  248. op: str = "",
  249. other: Optional[Var] = None,
  250. type_: Optional[Type] = None,
  251. flip: bool = False,
  252. fn: Optional[str] = None,
  253. ) -> Var:
  254. """Perform an operation on a var.
  255. Args:
  256. op: The operation to perform.
  257. other: The other var to perform the operation on.
  258. type_: The type of the operation result.
  259. flip: Whether to flip the order of the operation.
  260. fn: A function to apply to the operation.
  261. Returns:
  262. The operation result.
  263. """
  264. # Wrap strings in quotes.
  265. if isinstance(other, str):
  266. other = Var.create(json.dumps(other))
  267. else:
  268. other = Var.create(other)
  269. if type_ is None:
  270. type_ = self.type_
  271. if other is None:
  272. name = f"{op}{self.full_name}"
  273. else:
  274. props = (other, self) if flip else (self, other)
  275. name = f"{props[0].full_name} {op} {props[1].full_name}"
  276. if fn is None:
  277. name = format.wrap(name, "(")
  278. if fn is not None:
  279. name = f"{fn}({name})"
  280. return BaseVar(
  281. name=name,
  282. type_=type_,
  283. )
  284. def compare(self, op: str, other: Var) -> Var:
  285. """Compare two vars with inequalities.
  286. Args:
  287. op: The comparison operator.
  288. other: The other var to compare with.
  289. Returns:
  290. The comparison result.
  291. """
  292. return self.operation(op, other, bool)
  293. def __invert__(self) -> Var:
  294. """Invert a var.
  295. Returns:
  296. The inverted var.
  297. """
  298. return self.operation("!", type_=bool)
  299. def __neg__(self) -> Var:
  300. """Negate a var.
  301. Returns:
  302. The negated var.
  303. """
  304. return self.operation(fn="-")
  305. def __abs__(self) -> Var:
  306. """Get the absolute value of a var.
  307. Returns:
  308. A var with the absolute value.
  309. """
  310. return self.operation(fn="Math.abs")
  311. def length(self) -> Var:
  312. """Get the length of a list var.
  313. Returns:
  314. A var with the absolute value.
  315. Raises:
  316. TypeError: If the var is not a list.
  317. """
  318. if not types._issubclass(self.type_, List):
  319. raise TypeError(f"Cannot get length of non-list var {self}.")
  320. return BaseVar(
  321. name=f"{self.full_name}.length",
  322. type_=int,
  323. )
  324. def __eq__(self, other: Var) -> Var:
  325. """Perform an equality comparison.
  326. Args:
  327. other: The other var to compare with.
  328. Returns:
  329. A var representing the equality comparison.
  330. """
  331. return self.compare("===", other)
  332. def __ne__(self, other: Var) -> Var:
  333. """Perform an inequality comparison.
  334. Args:
  335. other: The other var to compare with.
  336. Returns:
  337. A var representing the inequality comparison.
  338. """
  339. return self.compare("!==", other)
  340. def __gt__(self, other: Var) -> Var:
  341. """Perform a greater than comparison.
  342. Args:
  343. other: The other var to compare with.
  344. Returns:
  345. A var representing the greater than comparison.
  346. """
  347. return self.compare(">", other)
  348. def __ge__(self, other: Var) -> Var:
  349. """Perform a greater than or equal to comparison.
  350. Args:
  351. other: The other var to compare with.
  352. Returns:
  353. A var representing the greater than or equal to comparison.
  354. """
  355. return self.compare(">=", other)
  356. def __lt__(self, other: Var) -> Var:
  357. """Perform a less than comparison.
  358. Args:
  359. other: The other var to compare with.
  360. Returns:
  361. A var representing the less than comparison.
  362. """
  363. return self.compare("<", other)
  364. def __le__(self, other: Var) -> Var:
  365. """Perform a less than or equal to comparison.
  366. Args:
  367. other: The other var to compare with.
  368. Returns:
  369. A var representing the less than or equal to comparison.
  370. """
  371. return self.compare("<=", other)
  372. def __add__(self, other: Var) -> Var:
  373. """Add two vars.
  374. Args:
  375. other: The other var to add.
  376. Returns:
  377. A var representing the sum.
  378. """
  379. return self.operation("+", other)
  380. def __radd__(self, other: Var) -> Var:
  381. """Add two vars.
  382. Args:
  383. other: The other var to add.
  384. Returns:
  385. A var representing the sum.
  386. """
  387. return self.operation("+", other, flip=True)
  388. def __sub__(self, other: Var) -> Var:
  389. """Subtract two vars.
  390. Args:
  391. other: The other var to subtract.
  392. Returns:
  393. A var representing the difference.
  394. """
  395. return self.operation("-", other)
  396. def __rsub__(self, other: Var) -> Var:
  397. """Subtract two vars.
  398. Args:
  399. other: The other var to subtract.
  400. Returns:
  401. A var representing the difference.
  402. """
  403. return self.operation("-", other, flip=True)
  404. def __mul__(self, other: Var) -> Var:
  405. """Multiply two vars.
  406. Args:
  407. other: The other var to multiply.
  408. Returns:
  409. A var representing the product.
  410. """
  411. return self.operation("*", other)
  412. def __rmul__(self, other: Var) -> Var:
  413. """Multiply two vars.
  414. Args:
  415. other: The other var to multiply.
  416. Returns:
  417. A var representing the product.
  418. """
  419. return self.operation("*", other, flip=True)
  420. def __pow__(self, other: Var) -> Var:
  421. """Raise a var to a power.
  422. Args:
  423. other: The power to raise to.
  424. Returns:
  425. A var representing the power.
  426. """
  427. return self.operation(",", other, fn="Math.pow")
  428. def __rpow__(self, other: Var) -> Var:
  429. """Raise a var to a power.
  430. Args:
  431. other: The power to raise to.
  432. Returns:
  433. A var representing the power.
  434. """
  435. return self.operation(",", other, flip=True, fn="Math.pow")
  436. def __truediv__(self, other: Var) -> Var:
  437. """Divide two vars.
  438. Args:
  439. other: The other var to divide.
  440. Returns:
  441. A var representing the quotient.
  442. """
  443. return self.operation("/", other)
  444. def __rtruediv__(self, other: Var) -> Var:
  445. """Divide two vars.
  446. Args:
  447. other: The other var to divide.
  448. Returns:
  449. A var representing the quotient.
  450. """
  451. return self.operation("/", other, flip=True)
  452. def __floordiv__(self, other: Var) -> Var:
  453. """Divide two vars.
  454. Args:
  455. other: The other var to divide.
  456. Returns:
  457. A var representing the quotient.
  458. """
  459. return self.operation("/", other, fn="Math.floor")
  460. def __mod__(self, other: Var) -> Var:
  461. """Get the remainder of two vars.
  462. Args:
  463. other: The other var to divide.
  464. Returns:
  465. A var representing the remainder.
  466. """
  467. return self.operation("%", other)
  468. def __rmod__(self, other: Var) -> Var:
  469. """Get the remainder of two vars.
  470. Args:
  471. other: The other var to divide.
  472. Returns:
  473. A var representing the remainder.
  474. """
  475. return self.operation("%", other, flip=True)
  476. def __and__(self, other: Var) -> Var:
  477. """Perform a logical and.
  478. Args:
  479. other: The other var to perform the logical and with.
  480. Returns:
  481. A var representing the logical and.
  482. """
  483. return self.operation("&&", other)
  484. def __rand__(self, other: Var) -> Var:
  485. """Perform a logical and.
  486. Args:
  487. other: The other var to perform the logical and with.
  488. Returns:
  489. A var representing the logical and.
  490. """
  491. return self.operation("&&", other, flip=True)
  492. def __or__(self, other: Var) -> Var:
  493. """Perform a logical or.
  494. Args:
  495. other: The other var to perform the logical or with.
  496. Returns:
  497. A var representing the logical or.
  498. """
  499. return self.operation("||", other)
  500. def __ror__(self, other: Var) -> Var:
  501. """Perform a logical or.
  502. Args:
  503. other: The other var to perform the logical or with.
  504. Returns:
  505. A var representing the logical or.
  506. """
  507. return self.operation("||", other, flip=True)
  508. def foreach(self, fn: Callable) -> Var:
  509. """Return a list of components. after doing a foreach on this var.
  510. Args:
  511. fn: The function to call on each component.
  512. Returns:
  513. A var representing foreach operation.
  514. """
  515. arg = BaseVar(
  516. name=get_unique_variable_name(),
  517. type_=self.type_,
  518. )
  519. return BaseVar(
  520. name=f"{self.full_name}.map(({arg.name}, i) => {fn(arg, key='i')})",
  521. type_=self.type_,
  522. )
  523. def to(self, type_: Type) -> Var:
  524. """Convert the type of the var.
  525. Args:
  526. type_: The type to convert to.
  527. Returns:
  528. The converted var.
  529. """
  530. return BaseVar(
  531. name=self.name,
  532. type_=type_,
  533. state=self.state,
  534. is_local=self.is_local,
  535. )
  536. @property
  537. def full_name(self) -> str:
  538. """Get the full name of the var.
  539. Returns:
  540. The full name of the var.
  541. """
  542. return self.name if self.state == "" else ".".join([self.state, self.name])
  543. def set_state(self, state: Type[State]) -> Any:
  544. """Set the state of the var.
  545. Args:
  546. state: The state to set.
  547. Returns:
  548. The var with the set state.
  549. """
  550. self.state = state.get_full_name()
  551. return self
  552. class BaseVar(Var, Base):
  553. """A base (non-computed) var of the app state."""
  554. # The name of the var.
  555. name: str
  556. # The type of the var.
  557. type_: Any
  558. # The name of the enclosing state.
  559. state: str = ""
  560. # Whether this is a local javascript variable.
  561. is_local: bool = False
  562. # Whether this var is a raw string.
  563. is_string: bool = False
  564. def __hash__(self) -> int:
  565. """Define a hash function for a var.
  566. Returns:
  567. The hash of the var.
  568. """
  569. return hash((self.name, str(self.type_)))
  570. def get_default_value(self) -> Any:
  571. """Get the default value of the var.
  572. Returns:
  573. The default value of the var.
  574. Raises:
  575. ImportError: If the var is a dataframe and pandas is not installed.
  576. """
  577. type_ = (
  578. self.type_.__origin__ if types.is_generic_alias(self.type_) else self.type_
  579. )
  580. if issubclass(type_, str):
  581. return ""
  582. if issubclass(type_, types.get_args(Union[int, float])):
  583. return 0
  584. if issubclass(type_, bool):
  585. return False
  586. if issubclass(type_, list):
  587. return []
  588. if issubclass(type_, dict):
  589. return {}
  590. if issubclass(type_, tuple):
  591. return ()
  592. if types.is_dataframe(type_):
  593. try:
  594. import pandas as pd
  595. return pd.DataFrame()
  596. except ImportError as e:
  597. raise ImportError(
  598. "Please install pandas to use dataframes in your app."
  599. ) from e
  600. return set() if issubclass(type_, set) else None
  601. def get_setter_name(self, include_state: bool = True) -> str:
  602. """Get the name of the var's generated setter function.
  603. Args:
  604. include_state: Whether to include the state name in the setter name.
  605. Returns:
  606. The name of the setter function.
  607. """
  608. setter = constants.SETTER_PREFIX + self.name
  609. if not include_state or self.state == "":
  610. return setter
  611. return ".".join((self.state, setter))
  612. def get_setter(self) -> Callable[[State, Any], None]:
  613. """Get the var's setter function.
  614. Returns:
  615. A function that that creates a setter for the var.
  616. """
  617. def setter(state: State, value: Any):
  618. """Get the setter for the var.
  619. Args:
  620. state: The state within which we add the setter function.
  621. value: The value to set.
  622. """
  623. setattr(state, self.name, value)
  624. setter.__qualname__ = self.get_setter_name()
  625. return setter
  626. class ComputedVar(Var, property):
  627. """A field with computed getters."""
  628. @property
  629. def name(self) -> str:
  630. """Get the name of the var.
  631. Returns:
  632. The name of the var.
  633. """
  634. assert self.fget is not None, "Var must have a getter."
  635. return self.fget.__name__
  636. @property
  637. def cache_attr(self) -> str:
  638. """Get the attribute used to cache the value on the instance.
  639. Returns:
  640. An attribute name.
  641. """
  642. return f"__cached_{self.name}"
  643. def __get__(self, instance, owner):
  644. """Get the ComputedVar value.
  645. If the value is already cached on the instance, return the cached value.
  646. If this ComputedVar doesn't know what type of object it is attached to, then save
  647. a reference as self.__objclass__.
  648. Args:
  649. instance: the instance of the class accessing this computed var.
  650. owner: the class that this descriptor is attached to.
  651. Returns:
  652. The value of the var for the given instance.
  653. """
  654. if not hasattr(self, "__objclass__"):
  655. self.__objclass__ = owner
  656. if instance is None:
  657. return super().__get__(instance, owner)
  658. # handle caching
  659. if not hasattr(instance, self.cache_attr):
  660. setattr(instance, self.cache_attr, super().__get__(instance, owner))
  661. return getattr(instance, self.cache_attr)
  662. def deps(self, obj: Optional[FunctionType] = None) -> Set[str]:
  663. """Determine var dependencies of this ComputedVar.
  664. Save references to attributes accessed on "self". Recursively called
  665. when the function makes a method call on "self".
  666. Args:
  667. obj: the object to disassemble (defaults to the fget function).
  668. Returns:
  669. A set of variable names accessed by the given obj.
  670. """
  671. d = set()
  672. if obj is None:
  673. if self.fget is not None:
  674. obj = cast(FunctionType, self.fget)
  675. else:
  676. return set()
  677. if not obj.__code__.co_varnames:
  678. # cannot reference self if method takes no args
  679. return set()
  680. self_name = obj.__code__.co_varnames[0]
  681. self_is_top_of_stack = False
  682. for instruction in dis.get_instructions(obj):
  683. if instruction.opname == "LOAD_FAST" and instruction.argval == self_name:
  684. self_is_top_of_stack = True
  685. continue
  686. if self_is_top_of_stack and instruction.opname == "LOAD_ATTR":
  687. d.add(instruction.argval)
  688. elif self_is_top_of_stack and instruction.opname == "LOAD_METHOD":
  689. d.update(self.deps(obj=getattr(self.__objclass__, instruction.argval)))
  690. self_is_top_of_stack = False
  691. return d
  692. def mark_dirty(self, instance) -> None:
  693. """Mark this ComputedVar as dirty.
  694. Args:
  695. instance: the state instance that needs to recompute the value.
  696. """
  697. with contextlib.suppress(AttributeError):
  698. delattr(instance, self.cache_attr)
  699. @property
  700. def type_(self):
  701. """Get the type of the var.
  702. Returns:
  703. The type of the var.
  704. """
  705. hints = get_type_hints(self.fget)
  706. if "return" in hints:
  707. return hints["return"]
  708. return Any
  709. class PCList(list):
  710. """A custom list that pynecone can detect its mutation."""
  711. def __init__(
  712. self,
  713. original_list: List,
  714. reassign_field: Callable = lambda _field_name: None,
  715. field_name: str = "",
  716. ):
  717. """Initialize PCList.
  718. Args:
  719. original_list (List): The original list
  720. reassign_field (Callable):
  721. The method in the parent state to reassign the field.
  722. Default to be a no-op function
  723. field_name (str): the name of field in the parent state
  724. """
  725. self._reassign_field = lambda: reassign_field(field_name)
  726. super().__init__(original_list)
  727. def append(self, *args, **kwargs):
  728. """Append.
  729. Args:
  730. args: The args passed.
  731. kwargs: The kwargs passed.
  732. """
  733. super().append(*args, **kwargs)
  734. self._reassign_field()
  735. def __setitem__(self, *args, **kwargs):
  736. """Set item.
  737. Args:
  738. args: The args passed.
  739. kwargs: The kwargs passed.
  740. """
  741. super().__setitem__(*args, **kwargs)
  742. self._reassign_field()
  743. def __delitem__(self, *args, **kwargs):
  744. """Delete item.
  745. Args:
  746. args: The args passed.
  747. kwargs: The kwargs passed.
  748. """
  749. super().__delitem__(*args, **kwargs)
  750. self._reassign_field()
  751. def clear(self, *args, **kwargs):
  752. """Remove all item from the list.
  753. Args:
  754. args: The args passed.
  755. kwargs: The kwargs passed.
  756. """
  757. super().clear(*args, **kwargs)
  758. self._reassign_field()
  759. def extend(self, *args, **kwargs):
  760. """Add all item of a list to the end of the list.
  761. Args:
  762. args: The args passed.
  763. kwargs: The kwargs passed.
  764. """
  765. super().extend(*args, **kwargs)
  766. self._reassign_field() if hasattr(self, "_reassign_field") else None
  767. def pop(self, *args, **kwargs):
  768. """Remove an element.
  769. Args:
  770. args: The args passed.
  771. kwargs: The kwargs passed.
  772. """
  773. super().pop(*args, **kwargs)
  774. self._reassign_field()
  775. def remove(self, *args, **kwargs):
  776. """Remove an element.
  777. Args:
  778. args: The args passed.
  779. kwargs: The kwargs passed.
  780. """
  781. super().remove(*args, **kwargs)
  782. self._reassign_field()
  783. class PCDict(dict):
  784. """A custom dict that pynecone can detect its mutation."""
  785. def __init__(
  786. self,
  787. original_dict: Dict,
  788. reassign_field: Callable = lambda _field_name: None,
  789. field_name: str = "",
  790. ):
  791. """Initialize PCDict.
  792. Args:
  793. original_dict: The original dict
  794. reassign_field:
  795. The method in the parent state to reassign the field.
  796. Default to be a no-op function
  797. field_name: the name of field in the parent state
  798. """
  799. super().__init__(original_dict)
  800. self._reassign_field = lambda: reassign_field(field_name)
  801. def clear(self):
  802. """Remove all item from the list."""
  803. super().clear()
  804. self._reassign_field()
  805. def setdefault(self, *args, **kwargs):
  806. """Return value of key if or set default.
  807. Args:
  808. args: The args passed.
  809. kwargs: The kwargs passed.
  810. """
  811. super().setdefault(*args, **kwargs)
  812. self._reassign_field()
  813. def popitem(self):
  814. """Pop last item."""
  815. super().popitem()
  816. self._reassign_field()
  817. def pop(self, k, d=None):
  818. """Remove an element.
  819. Args:
  820. k: The args passed.
  821. d: The kwargs passed.
  822. """
  823. super().pop(k, d)
  824. self._reassign_field()
  825. def update(self, *args, **kwargs):
  826. """Update the dict with another dict.
  827. Args:
  828. args: The args passed.
  829. kwargs: The kwargs passed.
  830. """
  831. super().update(*args, **kwargs)
  832. self._reassign_field()
  833. def __setitem__(self, *args, **kwargs):
  834. """Set an item in the dict.
  835. Args:
  836. args: The args passed.
  837. kwargs: The kwargs passed.
  838. """
  839. super().__setitem__(*args, **kwargs)
  840. self._reassign_field() if hasattr(self, "_reassign_field") else None
  841. def __delitem__(self, *args, **kwargs):
  842. """Delete an item in the dict.
  843. Args:
  844. args: The args passed.
  845. kwargs: The kwargs passed.
  846. """
  847. super().__delitem__(*args, **kwargs)
  848. self._reassign_field()
  849. class ImportVar(Base):
  850. """An import var."""
  851. # The name of the import tag.
  852. tag: Optional[str]
  853. # whether the import is default or named.
  854. is_default: Optional[bool] = False
  855. # The tag alias.
  856. alias: Optional[str] = None
  857. @property
  858. def name(self) -> str:
  859. """The name of the import.
  860. Returns:
  861. The name(tag name with alias) of tag.
  862. """
  863. return self.tag if not self.alias else " as ".join([self.tag, self.alias]) # type: ignore
  864. def __hash__(self) -> int:
  865. """Define a hash function for the import var.
  866. Returns:
  867. The hash of the var.
  868. """
  869. return hash((self.tag, self.is_default, self.alias))