var.py 25 KB

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