vars.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  1. """Define a state var."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import dis
  6. import inspect
  7. import json
  8. import random
  9. import re
  10. import string
  11. import sys
  12. from types import CodeType, FunctionType
  13. from typing import (
  14. TYPE_CHECKING,
  15. Any,
  16. Callable,
  17. Dict,
  18. Iterable,
  19. List,
  20. Literal,
  21. Optional,
  22. Set,
  23. Tuple,
  24. Type,
  25. Union,
  26. _GenericAlias, # type: ignore
  27. cast,
  28. get_args,
  29. get_origin,
  30. get_type_hints,
  31. )
  32. import pydantic
  33. from reflex import constants
  34. from reflex.base import Base
  35. from reflex.utils import console, format, imports, serializers, types
  36. # This module used to export ImportVar itself, so we still import it for export here
  37. from reflex.utils.imports import ImportDict, ImportVar
  38. if TYPE_CHECKING:
  39. from reflex.state import BaseState
  40. # Set of unique variable names.
  41. USED_VARIABLES = set()
  42. # Supported operators for all types.
  43. ALL_OPS = ["==", "!=", "!==", "===", "&&", "||"]
  44. # Delimiters used between function args or operands.
  45. DELIMITERS = [","]
  46. # Mapping of valid operations for different type combinations.
  47. OPERATION_MAPPING = {
  48. (int, int): {
  49. "+",
  50. "-",
  51. "/",
  52. "//",
  53. "*",
  54. "%",
  55. "**",
  56. ">",
  57. "<",
  58. "<=",
  59. ">=",
  60. "|",
  61. "&",
  62. },
  63. (int, str): {"*"},
  64. (int, list): {"*"},
  65. (str, str): {"+", ">", "<", "<=", ">="},
  66. (float, float): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  67. (float, int): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
  68. (list, list): {"+", ">", "<", "<=", ">="},
  69. }
  70. # These names were changed in reflex 0.3.0
  71. REPLACED_NAMES = {
  72. "full_name": "_var_full_name",
  73. "name": "_var_name",
  74. "state": "_var_data.state",
  75. "type_": "_var_type",
  76. "is_local": "_var_is_local",
  77. "is_string": "_var_is_string",
  78. "set_state": "_var_set_state",
  79. "deps": "_deps",
  80. }
  81. def get_unique_variable_name() -> str:
  82. """Get a unique variable name.
  83. Returns:
  84. The unique variable name.
  85. """
  86. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  87. if name not in USED_VARIABLES:
  88. USED_VARIABLES.add(name)
  89. return name
  90. return get_unique_variable_name()
  91. class VarData(Base):
  92. """Metadata associated with a Var."""
  93. # The name of the enclosing state.
  94. state: str = ""
  95. # Imports needed to render this var
  96. imports: ImportDict = {}
  97. # Hooks that need to be present in the component to render this var
  98. hooks: Set[str] = set()
  99. @classmethod
  100. def merge(cls, *others: VarData | None) -> VarData | None:
  101. """Merge multiple var data objects.
  102. Args:
  103. *others: The var data objects to merge.
  104. Returns:
  105. The merged var data object.
  106. """
  107. state = ""
  108. _imports = {}
  109. hooks = set()
  110. for var_data in others:
  111. if var_data is None:
  112. continue
  113. state = state or var_data.state
  114. _imports = imports.merge_imports(_imports, var_data.imports)
  115. hooks.update(var_data.hooks)
  116. return (
  117. cls(
  118. state=state,
  119. imports=_imports,
  120. hooks=hooks,
  121. )
  122. or None
  123. )
  124. def __bool__(self) -> bool:
  125. """Check if the var data is non-empty.
  126. Returns:
  127. True if any field is set to a non-default value.
  128. """
  129. return bool(self.state or self.imports or self.hooks)
  130. def __eq__(self, other: Any) -> bool:
  131. """Check if two var data objects are equal.
  132. Args:
  133. other: The other var data object to compare.
  134. Returns:
  135. True if all fields are equal and collapsed imports are equal.
  136. """
  137. if not isinstance(other, VarData):
  138. return False
  139. return (
  140. self.state == other.state
  141. and self.hooks == other.hooks
  142. and imports.collapse_imports(self.imports)
  143. == imports.collapse_imports(other.imports)
  144. )
  145. def dict(self) -> dict:
  146. """Convert the var data to a dictionary.
  147. Returns:
  148. The var data dictionary.
  149. """
  150. return {
  151. "state": self.state,
  152. "imports": {
  153. lib: [import_var.dict() for import_var in import_vars]
  154. for lib, import_vars in self.imports.items()
  155. },
  156. "hooks": list(self.hooks),
  157. }
  158. def _encode_var(value: Var) -> str:
  159. """Encode the state name into a formatted var.
  160. Args:
  161. value: The value to encode the state name into.
  162. Returns:
  163. The encoded var.
  164. """
  165. if value._var_data:
  166. return f"<reflex.Var>{value._var_data.json()}</reflex.Var>" + str(value)
  167. return str(value)
  168. def _decode_var(value: str) -> tuple[VarData | None, str]:
  169. """Decode the state name from a formatted var.
  170. Args:
  171. value: The value to extract the state name from.
  172. Returns:
  173. The extracted state name and the value without the state name.
  174. """
  175. var_datas = []
  176. if isinstance(value, str):
  177. # Extract the state name from a formatted var
  178. while m := re.match(r"(.*)<reflex.Var>(.*)</reflex.Var>(.*)", value):
  179. value = m.group(1) + m.group(3)
  180. try:
  181. var_datas.append(VarData.parse_raw(m.group(2)))
  182. except pydantic.ValidationError:
  183. # If the VarData is invalid, it was probably json-encoded twice...
  184. var_datas.append(VarData.parse_raw(json.loads(f'"{m.group(2)}"')))
  185. if var_datas:
  186. return VarData.merge(*var_datas), value
  187. return None, value
  188. def _extract_var_data(value: Iterable) -> list[VarData | None]:
  189. """Extract the var imports and hooks from an iterable containing a Var.
  190. Args:
  191. value: The iterable to extract the VarData from
  192. Returns:
  193. The extracted VarDatas.
  194. """
  195. var_datas = []
  196. with contextlib.suppress(TypeError):
  197. for sub in value:
  198. if isinstance(sub, Var):
  199. var_datas.append(sub._var_data)
  200. elif not isinstance(sub, str):
  201. # Recurse into dict values.
  202. if hasattr(sub, "values") and callable(sub.values):
  203. var_datas.extend(_extract_var_data(sub.values()))
  204. # Recurse into iterable values (or dict keys).
  205. var_datas.extend(_extract_var_data(sub))
  206. # Recurse when value is a dict itself.
  207. values = getattr(value, "values", None)
  208. if callable(values):
  209. var_datas.extend(_extract_var_data(values()))
  210. return var_datas
  211. class Var:
  212. """An abstract var."""
  213. # The name of the var.
  214. _var_name: str
  215. # The type of the var.
  216. _var_type: Type
  217. # Whether this is a local javascript variable.
  218. _var_is_local: bool
  219. # Whether the var is a string literal.
  220. _var_is_string: bool
  221. # _var_full_name should be prefixed with _var_state
  222. _var_full_name_needs_state_prefix: bool
  223. # Extra metadata associated with the Var
  224. _var_data: Optional[VarData]
  225. @classmethod
  226. def create(
  227. cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
  228. ) -> Var | None:
  229. """Create a var from a value.
  230. Args:
  231. value: The value to create the var from.
  232. _var_is_local: Whether the var is local.
  233. _var_is_string: Whether the var is a string literal.
  234. Returns:
  235. The var.
  236. Raises:
  237. TypeError: If the value is JSON-unserializable.
  238. """
  239. # Check for none values.
  240. if value is None:
  241. return None
  242. # If the value is already a var, do nothing.
  243. if isinstance(value, Var):
  244. return value
  245. # Try to pull the imports and hooks from contained values.
  246. _var_data = None
  247. if not isinstance(value, str):
  248. _var_data = VarData.merge(*_extract_var_data(value))
  249. # Try to serialize the value.
  250. type_ = type(value)
  251. name = value if type_ in types.JSONType else serializers.serialize(value)
  252. if name is None:
  253. raise TypeError(
  254. f"No JSON serializer found for var {value} of type {type_}."
  255. )
  256. name = name if isinstance(name, str) else format.json_dumps(name)
  257. return BaseVar(
  258. _var_name=name,
  259. _var_type=type_,
  260. _var_is_local=_var_is_local,
  261. _var_is_string=_var_is_string,
  262. _var_data=_var_data,
  263. )
  264. @classmethod
  265. def create_safe(
  266. cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
  267. ) -> Var:
  268. """Create a var from a value, asserting that it is not None.
  269. Args:
  270. value: The value to create the var from.
  271. _var_is_local: Whether the var is local.
  272. _var_is_string: Whether the var is a string literal.
  273. Returns:
  274. The var.
  275. """
  276. var = cls.create(
  277. value,
  278. _var_is_local=_var_is_local,
  279. _var_is_string=_var_is_string,
  280. )
  281. assert var is not None
  282. return var
  283. @classmethod
  284. def __class_getitem__(cls, type_: str) -> _GenericAlias:
  285. """Get a typed var.
  286. Args:
  287. type_: The type of the var.
  288. Returns:
  289. The var class item.
  290. """
  291. return _GenericAlias(cls, type_)
  292. def __post_init__(self) -> None:
  293. """Post-initialize the var."""
  294. # Decode any inline Var markup and apply it to the instance
  295. _var_data, _var_name = _decode_var(self._var_name)
  296. if _var_data:
  297. self._var_name = _var_name
  298. self._var_data = VarData.merge(self._var_data, _var_data)
  299. def _replace(self, merge_var_data=None, **kwargs: Any) -> Var:
  300. """Make a copy of this Var with updated fields.
  301. Args:
  302. merge_var_data: VarData to merge into the existing VarData.
  303. **kwargs: Var fields to update.
  304. Returns:
  305. A new BaseVar with the updated fields overwriting the corresponding fields in this Var.
  306. """
  307. field_values = dict(
  308. _var_name=kwargs.pop("_var_name", self._var_name),
  309. _var_type=kwargs.pop("_var_type", self._var_type),
  310. _var_is_local=kwargs.pop("_var_is_local", self._var_is_local),
  311. _var_is_string=kwargs.pop("_var_is_string", self._var_is_string),
  312. _var_full_name_needs_state_prefix=kwargs.pop(
  313. "_var_full_name_needs_state_prefix",
  314. self._var_full_name_needs_state_prefix,
  315. ),
  316. _var_data=VarData.merge(
  317. kwargs.get("_var_data", self._var_data), merge_var_data
  318. ),
  319. )
  320. return BaseVar(**field_values)
  321. def _decode(self) -> Any:
  322. """Decode Var as a python value.
  323. Note that Var with state set cannot be decoded python-side and will be
  324. returned as full_name.
  325. Returns:
  326. The decoded value or the Var name.
  327. """
  328. if self._var_is_string:
  329. return self._var_name
  330. try:
  331. return json.loads(self._var_name)
  332. except ValueError:
  333. return self._var_name
  334. def equals(self, other: Var) -> bool:
  335. """Check if two vars are equal.
  336. Args:
  337. other: The other var to compare.
  338. Returns:
  339. Whether the vars are equal.
  340. """
  341. return (
  342. self._var_name == other._var_name
  343. and self._var_type == other._var_type
  344. and self._var_is_local == other._var_is_local
  345. and self._var_full_name_needs_state_prefix
  346. == other._var_full_name_needs_state_prefix
  347. and self._var_data == other._var_data
  348. )
  349. def to_string(self, json: bool = True) -> Var:
  350. """Convert a var to a string.
  351. Args:
  352. json: Whether to convert to a JSON string.
  353. Returns:
  354. The stringified var.
  355. """
  356. fn = "JSON.stringify" if json else "String"
  357. return self.operation(fn=fn, type_=str)
  358. def __hash__(self) -> int:
  359. """Define a hash function for a var.
  360. Returns:
  361. The hash of the var.
  362. """
  363. return hash((self._var_name, str(self._var_type)))
  364. def __str__(self) -> str:
  365. """Wrap the var so it can be used in templates.
  366. Returns:
  367. The wrapped var, i.e. {state.var}.
  368. """
  369. out = (
  370. self._var_full_name
  371. if self._var_is_local
  372. else format.wrap(self._var_full_name, "{")
  373. )
  374. if self._var_is_string:
  375. out = format.format_string(out)
  376. return out
  377. def __bool__(self) -> bool:
  378. """Raise exception if using Var in a boolean context.
  379. Raises:
  380. TypeError: when attempting to bool-ify the Var.
  381. """
  382. raise TypeError(
  383. f"Cannot convert Var {self._var_full_name!r} to bool for use with `if`, `and`, `or`, and `not`. "
  384. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  385. )
  386. def __iter__(self) -> Any:
  387. """Raise exception if using Var in an iterable context.
  388. Raises:
  389. TypeError: when attempting to iterate over the Var.
  390. """
  391. raise TypeError(
  392. f"Cannot iterate over Var {self._var_full_name!r}. Instead use `rx.foreach`."
  393. )
  394. def __format__(self, format_spec: str) -> str:
  395. """Format the var into a Javascript equivalent to an f-string.
  396. Args:
  397. format_spec: The format specifier (Ignored for now).
  398. Returns:
  399. The formatted var.
  400. """
  401. # Encode the _var_data into the formatted output for tracking purposes.
  402. str_self = _encode_var(self)
  403. if self._var_is_local:
  404. return str_self
  405. return f"${str_self}"
  406. def __getitem__(self, i: Any) -> Var:
  407. """Index into a var.
  408. Args:
  409. i: The index to index into.
  410. Returns:
  411. The indexed var.
  412. Raises:
  413. TypeError: If the var is not indexable.
  414. """
  415. # Indexing is only supported for strings, lists, tuples, dicts, and dataframes.
  416. if not (
  417. types._issubclass(self._var_type, Union[List, Dict, Tuple, str])
  418. or types.is_dataframe(self._var_type)
  419. ):
  420. if self._var_type == Any:
  421. raise TypeError(
  422. "Could not index into var of type Any. (If you are trying to index into a state var, "
  423. "add the correct type annotation to the var.)"
  424. )
  425. raise TypeError(
  426. f"Var {self._var_name} of type {self._var_type} does not support indexing."
  427. )
  428. # The type of the indexed var.
  429. type_ = Any
  430. # Convert any vars to local vars.
  431. if isinstance(i, Var):
  432. i = i._replace(_var_is_local=True)
  433. # Handle list/tuple/str indexing.
  434. if types._issubclass(self._var_type, Union[List, Tuple, str]):
  435. # List/Tuple/String indices must be ints, slices, or vars.
  436. if (
  437. not isinstance(i, types.get_args(Union[int, slice, Var]))
  438. or isinstance(i, Var)
  439. and not i._var_type == int
  440. ):
  441. raise TypeError("Index must be an integer or an integer var.")
  442. # Handle slices first.
  443. if isinstance(i, slice):
  444. # Get the start and stop indices.
  445. start = i.start or 0
  446. stop = i.stop or "undefined"
  447. # Use the slice function.
  448. return self._replace(
  449. _var_name=f"{self._var_name}.slice({start}, {stop})",
  450. _var_is_string=False,
  451. )
  452. # Get the type of the indexed var.
  453. type_ = (
  454. types.get_args(self._var_type)[0]
  455. if types.is_generic_alias(self._var_type)
  456. else Any
  457. )
  458. # Use `at` to support negative indices.
  459. return self._replace(
  460. _var_name=f"{self._var_name}.at({i})",
  461. _var_type=type_,
  462. _var_is_string=False,
  463. )
  464. # Dictionary / dataframe indexing.
  465. # Tuples are currently not supported as indexes.
  466. if (
  467. (
  468. types._issubclass(self._var_type, Dict)
  469. or types.is_dataframe(self._var_type)
  470. )
  471. and not isinstance(i, types.get_args(Union[int, str, float, Var]))
  472. ) or (
  473. isinstance(i, Var)
  474. and not types._issubclass(
  475. i._var_type, types.get_args(Union[int, str, float])
  476. )
  477. ):
  478. raise TypeError(
  479. "Index must be one of the following types: int, str, int or str Var"
  480. )
  481. # Get the type of the indexed var.
  482. if isinstance(i, str):
  483. i = format.wrap(i, '"')
  484. type_ = (
  485. types.get_args(self._var_type)[1]
  486. if types.is_generic_alias(self._var_type)
  487. else Any
  488. )
  489. # Use normal indexing here.
  490. return self._replace(
  491. _var_name=f"{self._var_name}[{i}]",
  492. _var_type=type_,
  493. _var_is_string=False,
  494. )
  495. def __getattr__(self, name: str) -> Var:
  496. """Get a var attribute.
  497. Args:
  498. name: The name of the attribute.
  499. Returns:
  500. The var attribute.
  501. Raises:
  502. AttributeError: If the var is wrongly annotated or can't find attribute.
  503. TypeError: If an annotation to the var isn't provided.
  504. """
  505. # Check if the attribute is one of the class fields.
  506. if not name.startswith("_"):
  507. if self._var_type == Any:
  508. raise TypeError(
  509. f"You must provide an annotation for the state var `{self._var_full_name}`. Annotation cannot be `{self._var_type}`"
  510. ) from None
  511. is_optional = types.is_optional(self._var_type)
  512. type_ = types.get_attribute_access_type(self._var_type, name)
  513. if type_ is not None:
  514. return self._replace(
  515. _var_name=f"{self._var_name}{'?' if is_optional else ''}.{name}",
  516. _var_type=type_,
  517. _var_is_string=False,
  518. )
  519. if name in REPLACED_NAMES:
  520. raise AttributeError(
  521. f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
  522. )
  523. raise AttributeError(
  524. f"The State var `{self._var_full_name}` has no attribute '{name}' or may have been annotated "
  525. f"wrongly."
  526. )
  527. raise AttributeError(
  528. f"The State var has no attribute '{name}' or may have been annotated wrongly.",
  529. )
  530. def operation(
  531. self,
  532. op: str = "",
  533. other: Var | None = None,
  534. type_: Type | None = None,
  535. flip: bool = False,
  536. fn: str | None = None,
  537. invoke_fn: bool = False,
  538. ) -> Var:
  539. """Perform an operation on a var.
  540. Args:
  541. op: The operation to perform.
  542. other: The other var to perform the operation on.
  543. type_: The type of the operation result.
  544. flip: Whether to flip the order of the operation.
  545. fn: A function to apply to the operation.
  546. invoke_fn: Whether to invoke the function.
  547. Returns:
  548. The operation result.
  549. Raises:
  550. TypeError: If the operation between two operands is invalid.
  551. ValueError: If flip is set to true and value of operand is not provided
  552. """
  553. if isinstance(other, str):
  554. other = Var.create(json.dumps(other))
  555. else:
  556. other = Var.create(other)
  557. type_ = type_ or self._var_type
  558. if other is None and flip:
  559. raise ValueError(
  560. "flip_operands cannot be set to True if the value of 'other' operand is not provided"
  561. )
  562. left_operand, right_operand = (other, self) if flip else (self, other)
  563. if other is not None:
  564. # check if the operation between operands is valid.
  565. if op and not self.is_valid_operation(
  566. types.get_base_class(left_operand._var_type), # type: ignore
  567. types.get_base_class(right_operand._var_type), # type: ignore
  568. op,
  569. ):
  570. raise TypeError(
  571. f"Unsupported Operand type(s) for {op}: `{left_operand._var_full_name}` of type {left_operand._var_type.__name__} and `{right_operand._var_full_name}` of type {right_operand._var_type.__name__}" # type: ignore
  572. )
  573. # apply function to operands
  574. if fn is not None:
  575. if invoke_fn:
  576. # invoke the function on left operand.
  577. operation_name = f"{left_operand._var_full_name}.{fn}({right_operand._var_full_name})" # type: ignore
  578. else:
  579. # pass the operands as arguments to the function.
  580. operation_name = f"{left_operand._var_full_name} {op} {right_operand._var_full_name}" # type: ignore
  581. operation_name = f"{fn}({operation_name})"
  582. else:
  583. # apply operator to operands (left operand <operator> right_operand)
  584. operation_name = f"{left_operand._var_full_name} {op} {right_operand._var_full_name}" # type: ignore
  585. operation_name = format.wrap(operation_name, "(")
  586. else:
  587. # apply operator to left operand (<operator> left_operand)
  588. operation_name = f"{op}{self._var_full_name}"
  589. # apply function to operands
  590. if fn is not None:
  591. operation_name = (
  592. f"{fn}({operation_name})"
  593. if not invoke_fn
  594. else f"{self._var_full_name}.{fn}()"
  595. )
  596. return self._replace(
  597. _var_name=operation_name,
  598. _var_type=type_,
  599. _var_is_string=False,
  600. _var_full_name_needs_state_prefix=False,
  601. merge_var_data=other._var_data if other is not None else None,
  602. )
  603. @staticmethod
  604. def is_valid_operation(
  605. operand1_type: Type, operand2_type: Type, operator: str
  606. ) -> bool:
  607. """Check if an operation between two operands is valid.
  608. Args:
  609. operand1_type: Type of the operand
  610. operand2_type: Type of the second operand
  611. operator: The operator.
  612. Returns:
  613. Whether operation is valid or not
  614. """
  615. if operator in ALL_OPS or operator in DELIMITERS:
  616. return True
  617. # bools are subclasses of ints
  618. pair = tuple(
  619. sorted(
  620. [
  621. int if operand1_type == bool else operand1_type,
  622. int if operand2_type == bool else operand2_type,
  623. ],
  624. key=lambda x: x.__name__,
  625. )
  626. )
  627. return pair in OPERATION_MAPPING and operator in OPERATION_MAPPING[pair]
  628. def compare(self, op: str, other: Var) -> Var:
  629. """Compare two vars with inequalities.
  630. Args:
  631. op: The comparison operator.
  632. other: The other var to compare with.
  633. Returns:
  634. The comparison result.
  635. """
  636. return self.operation(op, other, bool)
  637. def __invert__(self) -> Var:
  638. """Invert a var.
  639. Returns:
  640. The inverted var.
  641. """
  642. return self.operation("!", type_=bool)
  643. def __neg__(self) -> Var:
  644. """Negate a var.
  645. Returns:
  646. The negated var.
  647. """
  648. return self.operation(fn="-")
  649. def __abs__(self) -> Var:
  650. """Get the absolute value of a var.
  651. Returns:
  652. A var with the absolute value.
  653. """
  654. return self.operation(fn="Math.abs")
  655. def length(self) -> Var:
  656. """Get the length of a list var.
  657. Returns:
  658. A var with the absolute value.
  659. Raises:
  660. TypeError: If the var is not a list.
  661. """
  662. if not types._issubclass(self._var_type, List):
  663. raise TypeError(f"Cannot get length of non-list var {self}.")
  664. return self._replace(
  665. _var_name=f"{self._var_name}.length",
  666. _var_type=int,
  667. _var_is_string=False,
  668. )
  669. def __eq__(self, other: Var) -> Var:
  670. """Perform an equality comparison.
  671. Args:
  672. other: The other var to compare with.
  673. Returns:
  674. A var representing the equality comparison.
  675. """
  676. return self.compare("===", other)
  677. def __ne__(self, other: Var) -> Var:
  678. """Perform an inequality comparison.
  679. Args:
  680. other: The other var to compare with.
  681. Returns:
  682. A var representing the inequality comparison.
  683. """
  684. return self.compare("!==", other)
  685. def __gt__(self, other: Var) -> Var:
  686. """Perform a greater than comparison.
  687. Args:
  688. other: The other var to compare with.
  689. Returns:
  690. A var representing the greater than comparison.
  691. """
  692. return self.compare(">", other)
  693. def __ge__(self, other: Var) -> Var:
  694. """Perform a greater than or equal to comparison.
  695. Args:
  696. other: The other var to compare with.
  697. Returns:
  698. A var representing the greater than or equal to comparison.
  699. """
  700. return self.compare(">=", other)
  701. def __lt__(self, other: Var) -> Var:
  702. """Perform a less than comparison.
  703. Args:
  704. other: The other var to compare with.
  705. Returns:
  706. A var representing the less than comparison.
  707. """
  708. return self.compare("<", other)
  709. def __le__(self, other: Var) -> Var:
  710. """Perform a less than or equal to comparison.
  711. Args:
  712. other: The other var to compare with.
  713. Returns:
  714. A var representing the less than or equal to comparison.
  715. """
  716. return self.compare("<=", other)
  717. def __add__(self, other: Var, flip=False) -> Var:
  718. """Add two vars.
  719. Args:
  720. other: The other var to add.
  721. flip: Whether to flip operands.
  722. Returns:
  723. A var representing the sum.
  724. """
  725. other_type = other._var_type if isinstance(other, Var) else type(other)
  726. # For list-list addition, javascript concatenates the content of the lists instead of
  727. # merging the list, and for that reason we use the spread operator available through spreadArraysOrObjects
  728. # utility function
  729. if (
  730. types.get_base_class(self._var_type) == list
  731. and types.get_base_class(other_type) == list
  732. ):
  733. return self.operation(
  734. ",", other, fn="spreadArraysOrObjects", flip=flip
  735. )._replace(
  736. merge_var_data=VarData(
  737. imports={
  738. f"/{constants.Dirs.STATE_PATH}": [
  739. ImportVar(tag="spreadArraysOrObjects")
  740. ]
  741. },
  742. ),
  743. )
  744. return self.operation("+", other, flip=flip)
  745. def __radd__(self, other: Var) -> Var:
  746. """Add two vars.
  747. Args:
  748. other: The other var to add.
  749. Returns:
  750. A var representing the sum.
  751. """
  752. return self.__add__(other=other, flip=True)
  753. def __sub__(self, other: Var) -> Var:
  754. """Subtract two vars.
  755. Args:
  756. other: The other var to subtract.
  757. Returns:
  758. A var representing the difference.
  759. """
  760. return self.operation("-", other)
  761. def __rsub__(self, other: Var) -> Var:
  762. """Subtract two vars.
  763. Args:
  764. other: The other var to subtract.
  765. Returns:
  766. A var representing the difference.
  767. """
  768. return self.operation("-", other, flip=True)
  769. def __mul__(self, other: Var, flip=True) -> Var:
  770. """Multiply two vars.
  771. Args:
  772. other: The other var to multiply.
  773. flip: Whether to flip operands
  774. Returns:
  775. A var representing the product.
  776. """
  777. other_type = other._var_type if isinstance(other, Var) else type(other)
  778. # For str-int multiplication, we use the repeat function.
  779. # i.e "hello" * 2 is equivalent to "hello".repeat(2) in js.
  780. if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
  781. (int, str),
  782. (str, int),
  783. ]:
  784. return self.operation(other=other, fn="repeat", invoke_fn=True)
  785. # For list-int multiplication, we use the Array function.
  786. # i.e ["hello"] * 2 is equivalent to Array(2).fill().map(() => ["hello"]).flat() in js.
  787. if (types.get_base_class(self._var_type), types.get_base_class(other_type)) in [
  788. (int, list),
  789. (list, int),
  790. ]:
  791. other_name = other._var_full_name if isinstance(other, Var) else other
  792. name = f"Array({other_name}).fill().map(() => {self._var_full_name}).flat()"
  793. return self._replace(
  794. _var_name=name,
  795. _var_type=str,
  796. _var_is_string=False,
  797. _var_full_name_needs_state_prefix=False,
  798. )
  799. return self.operation("*", other)
  800. def __rmul__(self, other: Var) -> Var:
  801. """Multiply two vars.
  802. Args:
  803. other: The other var to multiply.
  804. Returns:
  805. A var representing the product.
  806. """
  807. return self.__mul__(other=other, flip=True)
  808. def __pow__(self, other: Var) -> Var:
  809. """Raise a var to a power.
  810. Args:
  811. other: The power to raise to.
  812. Returns:
  813. A var representing the power.
  814. """
  815. return self.operation(",", other, fn="Math.pow")
  816. def __rpow__(self, other: Var) -> Var:
  817. """Raise a var to a power.
  818. Args:
  819. other: The power to raise to.
  820. Returns:
  821. A var representing the power.
  822. """
  823. return self.operation(",", other, flip=True, fn="Math.pow")
  824. def __truediv__(self, other: Var) -> Var:
  825. """Divide two vars.
  826. Args:
  827. other: The other var to divide.
  828. Returns:
  829. A var representing the quotient.
  830. """
  831. return self.operation("/", other)
  832. def __rtruediv__(self, other: Var) -> Var:
  833. """Divide two vars.
  834. Args:
  835. other: The other var to divide.
  836. Returns:
  837. A var representing the quotient.
  838. """
  839. return self.operation("/", other, flip=True)
  840. def __floordiv__(self, other: Var) -> Var:
  841. """Divide two vars.
  842. Args:
  843. other: The other var to divide.
  844. Returns:
  845. A var representing the quotient.
  846. """
  847. return self.operation("/", other, fn="Math.floor")
  848. def __mod__(self, other: Var) -> Var:
  849. """Get the remainder of two vars.
  850. Args:
  851. other: The other var to divide.
  852. Returns:
  853. A var representing the remainder.
  854. """
  855. return self.operation("%", other)
  856. def __rmod__(self, other: Var) -> Var:
  857. """Get the remainder of two vars.
  858. Args:
  859. other: The other var to divide.
  860. Returns:
  861. A var representing the remainder.
  862. """
  863. return self.operation("%", other, flip=True)
  864. def __and__(self, other: Var) -> Var:
  865. """Perform a logical and.
  866. Args:
  867. other: The other var to perform the logical AND with.
  868. Returns:
  869. A var representing the logical AND.
  870. Note:
  871. This method provides behavior specific to JavaScript, where it returns the JavaScript
  872. equivalent code (using the '&&' operator) of a logical AND operation.
  873. In JavaScript, the
  874. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  875. by returning the equivalent code as a Var instance.
  876. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  877. it challenging to override the behavior entirely.
  878. Therefore, this method leverages the
  879. bitwise AND '__and__' operator for custom JavaScript-like behavior.
  880. Example:
  881. >>> var1 = Var.create(True)
  882. >>> var2 = Var.create(False)
  883. >>> js_code = var1 & var2
  884. >>> print(js_code._var_full_name)
  885. '(true && false)'
  886. """
  887. return self.operation("&&", other, type_=bool)
  888. def __rand__(self, other: Var) -> Var:
  889. """Perform a logical and.
  890. Args:
  891. other: The other var to perform the logical AND with.
  892. Returns:
  893. A var representing the logical AND.
  894. Note:
  895. This method provides behavior specific to JavaScript, where it returns the JavaScript
  896. equivalent code (using the '&&' operator) of a logical AND operation.
  897. In JavaScript, the
  898. logical OR operator '&&' is used for Boolean logic, and this method emulates that behavior
  899. by returning the equivalent code as a Var instance.
  900. In Python, logical AND 'and' operates differently, evaluating expressions immediately, making
  901. it challenging to override the behavior entirely.
  902. Therefore, this method leverages the
  903. bitwise AND '__rand__' operator for custom JavaScript-like behavior.
  904. Example:
  905. >>> var1 = Var.create(True)
  906. >>> var2 = Var.create(False)
  907. >>> js_code = var1 & var2
  908. >>> print(js_code._var_full_name)
  909. '(false && true)'
  910. """
  911. return self.operation("&&", other, type_=bool, flip=True)
  912. def __or__(self, other: Var) -> Var:
  913. """Perform a logical or.
  914. Args:
  915. other: The other var to perform the logical or with.
  916. Returns:
  917. A var representing the logical or.
  918. Note:
  919. This method provides behavior specific to JavaScript, where it returns the JavaScript
  920. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  921. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  922. by returning the equivalent code as a Var instance.
  923. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  924. it challenging to override the behavior entirely. Therefore, this method leverages the
  925. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  926. Example:
  927. >>> var1 = Var.create(True)
  928. >>> var2 = Var.create(False)
  929. >>> js_code = var1 | var2
  930. >>> print(js_code._var_full_name)
  931. '(true || false)'
  932. """
  933. return self.operation("||", other, type_=bool)
  934. def __ror__(self, other: Var) -> Var:
  935. """Perform a logical or.
  936. Args:
  937. other: The other var to perform the logical or with.
  938. Returns:
  939. A var representing the logical or.
  940. Note:
  941. This method provides behavior specific to JavaScript, where it returns the JavaScript
  942. equivalent code (using the '||' operator) of a logical OR operation. In JavaScript, the
  943. logical OR operator '||' is used for Boolean logic, and this method emulates that behavior
  944. by returning the equivalent code as a Var instance.
  945. In Python, logical OR 'or' operates differently, evaluating expressions immediately, making
  946. it challenging to override the behavior entirely. Therefore, this method leverages the
  947. bitwise OR '__or__' operator for custom JavaScript-like behavior.
  948. Example:
  949. >>> var1 = Var.create(True)
  950. >>> var2 = Var.create(False)
  951. >>> js_code = var1 | var2
  952. >>> print(js_code)
  953. 'false || true'
  954. """
  955. return self.operation("||", other, type_=bool, flip=True)
  956. def __contains__(self, _: Any) -> Var:
  957. """Override the 'in' operator to alert the user that it is not supported.
  958. Raises:
  959. TypeError: the operation is not supported
  960. """
  961. raise TypeError(
  962. "'in' operator not supported for Var types, use Var.contains() instead."
  963. )
  964. def contains(self, other: Any) -> Var:
  965. """Check if a var contains the object `other`.
  966. Args:
  967. other: The object to check.
  968. Raises:
  969. TypeError: If the var is not a valid type: dict, list, tuple or str.
  970. Returns:
  971. A var representing the contain check.
  972. """
  973. if not (types._issubclass(self._var_type, Union[dict, list, tuple, str])):
  974. raise TypeError(
  975. f"Var {self._var_full_name} of type {self._var_type} does not support contains check."
  976. )
  977. method = (
  978. "hasOwnProperty"
  979. if types.get_base_class(self._var_type) == dict
  980. else "includes"
  981. )
  982. if isinstance(other, str):
  983. other = Var.create(json.dumps(other), _var_is_string=True)
  984. elif not isinstance(other, Var):
  985. other = Var.create(other)
  986. if types._issubclass(self._var_type, Dict):
  987. return self._replace(
  988. _var_name=f"{self._var_name}.{method}({other._var_full_name})",
  989. _var_type=bool,
  990. _var_is_string=False,
  991. merge_var_data=other._var_data,
  992. )
  993. else: # str, list, tuple
  994. # For strings, the left operand must be a string.
  995. if types._issubclass(self._var_type, str) and not types._issubclass(
  996. other._var_type, str
  997. ):
  998. raise TypeError(
  999. f"'in <string>' requires string as left operand, not {other._var_type}"
  1000. )
  1001. return self._replace(
  1002. _var_name=f"{self._var_name}.includes({other._var_full_name})",
  1003. _var_type=bool,
  1004. _var_is_string=False,
  1005. merge_var_data=other._var_data,
  1006. )
  1007. def reverse(self) -> Var:
  1008. """Reverse a list var.
  1009. Raises:
  1010. TypeError: If the var is not a list.
  1011. Returns:
  1012. A var with the reversed list.
  1013. """
  1014. if not types._issubclass(self._var_type, list):
  1015. raise TypeError(f"Cannot reverse non-list var {self._var_full_name}.")
  1016. return self._replace(
  1017. _var_name=f"[...{self._var_full_name}].reverse()",
  1018. _var_is_string=False,
  1019. _var_full_name_needs_state_prefix=False,
  1020. )
  1021. def lower(self) -> Var:
  1022. """Convert a string var to lowercase.
  1023. Returns:
  1024. A var with the lowercase string.
  1025. Raises:
  1026. TypeError: If the var is not a string.
  1027. """
  1028. if not types._issubclass(self._var_type, str):
  1029. raise TypeError(
  1030. f"Cannot convert non-string var {self._var_full_name} to lowercase."
  1031. )
  1032. return self._replace(
  1033. _var_name=f"{self._var_name}.toLowerCase()",
  1034. _var_is_string=False,
  1035. _var_type=str,
  1036. )
  1037. def upper(self) -> Var:
  1038. """Convert a string var to uppercase.
  1039. Returns:
  1040. A var with the uppercase string.
  1041. Raises:
  1042. TypeError: If the var is not a string.
  1043. """
  1044. if not types._issubclass(self._var_type, str):
  1045. raise TypeError(
  1046. f"Cannot convert non-string var {self._var_full_name} to uppercase."
  1047. )
  1048. return self._replace(
  1049. _var_name=f"{self._var_name}.toUpperCase()",
  1050. _var_is_string=False,
  1051. _var_type=str,
  1052. )
  1053. def split(self, other: str | Var[str] = " ") -> Var:
  1054. """Split a string var into a list.
  1055. Args:
  1056. other: The string to split the var with.
  1057. Returns:
  1058. A var with the list.
  1059. Raises:
  1060. TypeError: If the var is not a string.
  1061. """
  1062. if not types._issubclass(self._var_type, str):
  1063. raise TypeError(f"Cannot split non-string var {self._var_full_name}.")
  1064. other = Var.create_safe(json.dumps(other)) if isinstance(other, str) else other
  1065. return self._replace(
  1066. _var_name=f"{self._var_name}.split({other._var_full_name})",
  1067. _var_is_string=False,
  1068. _var_type=list[str],
  1069. merge_var_data=other._var_data,
  1070. )
  1071. def join(self, other: str | Var[str] | None = None) -> Var:
  1072. """Join a list var into a string.
  1073. Args:
  1074. other: The string to join the list with.
  1075. Returns:
  1076. A var with the string.
  1077. Raises:
  1078. TypeError: If the var is not a list.
  1079. """
  1080. if not types._issubclass(self._var_type, list):
  1081. raise TypeError(f"Cannot join non-list var {self._var_full_name}.")
  1082. if other is None:
  1083. other = Var.create_safe('""')
  1084. if isinstance(other, str):
  1085. other = Var.create_safe(json.dumps(other))
  1086. else:
  1087. other = Var.create_safe(other)
  1088. return self._replace(
  1089. _var_name=f"{self._var_name}.join({other._var_full_name})",
  1090. _var_is_string=False,
  1091. _var_type=str,
  1092. merge_var_data=other._var_data,
  1093. )
  1094. def foreach(self, fn: Callable) -> Var:
  1095. """Return a list of components. after doing a foreach on this var.
  1096. Args:
  1097. fn: The function to call on each component.
  1098. Returns:
  1099. A var representing foreach operation.
  1100. Raises:
  1101. TypeError: If the var is not a list.
  1102. """
  1103. inner_types = get_args(self._var_type)
  1104. if not inner_types:
  1105. raise TypeError(
  1106. f"Cannot foreach over non-sequence var {self._var_full_name} of type {self._var_type}."
  1107. )
  1108. arg = BaseVar(
  1109. _var_name=get_unique_variable_name(),
  1110. _var_type=inner_types[0],
  1111. )
  1112. index = BaseVar(
  1113. _var_name=get_unique_variable_name(),
  1114. _var_type=int,
  1115. )
  1116. fn_signature = inspect.signature(fn)
  1117. fn_args = (arg, index)
  1118. fn_ret = fn(*fn_args[: len(fn_signature.parameters)])
  1119. return self._replace(
  1120. _var_name=f"{self._var_full_name}.map(({arg._var_name}, {index._var_name}) => {fn_ret})",
  1121. _var_is_string=False,
  1122. )
  1123. @classmethod
  1124. def range(
  1125. cls,
  1126. v1: Var | int = 0,
  1127. v2: Var | int | None = None,
  1128. step: Var | int | None = None,
  1129. ) -> Var:
  1130. """Return an iterator over indices from v1 to v2 (or 0 to v1).
  1131. Args:
  1132. v1: The start of the range or end of range if v2 is not given.
  1133. v2: The end of the range.
  1134. step: The number of numbers between each item.
  1135. Returns:
  1136. A var representing range operation.
  1137. Raises:
  1138. TypeError: If the var is not an int.
  1139. """
  1140. if not isinstance(v1, Var):
  1141. v1 = Var.create_safe(v1)
  1142. if v1._var_type != int:
  1143. raise TypeError(f"Cannot get range on non-int var {v1._var_full_name}.")
  1144. if not isinstance(v2, Var):
  1145. v2 = Var.create(v2)
  1146. if v2 is None:
  1147. v2 = Var.create_safe("undefined")
  1148. elif v2._var_type != int:
  1149. raise TypeError(f"Cannot get range on non-int var {v2._var_full_name}.")
  1150. if not isinstance(step, Var):
  1151. step = Var.create(step)
  1152. if step is None:
  1153. step = Var.create_safe(1)
  1154. elif step._var_type != int:
  1155. raise TypeError(f"Cannot get range on non-int var {step._var_full_name}.")
  1156. return BaseVar(
  1157. _var_name=f"Array.from(range({v1._var_full_name}, {v2._var_full_name}, {step._var_name}))",
  1158. _var_type=list[int],
  1159. _var_is_local=False,
  1160. _var_data=VarData.merge(
  1161. v1._var_data,
  1162. v2._var_data,
  1163. step._var_data,
  1164. VarData(
  1165. imports={
  1166. "/utils/helpers/range.js": [
  1167. ImportVar(tag="range", is_default=True),
  1168. ],
  1169. },
  1170. ),
  1171. ),
  1172. )
  1173. def to(self, type_: Type) -> Var:
  1174. """Convert the type of the var.
  1175. Args:
  1176. type_: The type to convert to.
  1177. Returns:
  1178. The converted var.
  1179. """
  1180. return self._replace(_var_type=type_)
  1181. def as_ref(self) -> Var:
  1182. """Convert the var to a ref.
  1183. Returns:
  1184. The var as a ref.
  1185. """
  1186. return self._replace(
  1187. _var_name=f"refs['{self._var_full_name}']",
  1188. _var_is_local=True,
  1189. _var_is_string=False,
  1190. _var_full_name_needs_state_prefix=False,
  1191. merge_var_data=VarData(
  1192. imports={
  1193. f"/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")],
  1194. },
  1195. ),
  1196. )
  1197. @property
  1198. def _var_full_name(self) -> str:
  1199. """Get the full name of the var.
  1200. Returns:
  1201. The full name of the var.
  1202. """
  1203. if not self._var_full_name_needs_state_prefix:
  1204. return self._var_name
  1205. return (
  1206. self._var_name
  1207. if self._var_data is None or self._var_data.state == ""
  1208. else ".".join(
  1209. [format.format_state_name(self._var_data.state), self._var_name]
  1210. )
  1211. )
  1212. def _var_set_state(self, state: Type[BaseState] | str) -> Any:
  1213. """Set the state of the var.
  1214. Args:
  1215. state: The state to set or the full name of the state.
  1216. Returns:
  1217. The var with the set state.
  1218. """
  1219. state_name = state if isinstance(state, str) else state.get_full_name()
  1220. new_var_data = VarData(
  1221. state=state_name,
  1222. hooks={
  1223. "const {0} = useContext(StateContexts.{0})".format(
  1224. format.format_state_name(state_name)
  1225. )
  1226. },
  1227. imports={
  1228. f"/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  1229. "react": [ImportVar(tag="useContext")],
  1230. },
  1231. )
  1232. self._var_data = VarData.merge(self._var_data, new_var_data)
  1233. self._var_full_name_needs_state_prefix = True
  1234. return self
  1235. @property
  1236. def _var_state(self) -> str:
  1237. """Compat method for getting the state.
  1238. Returns:
  1239. The state name associated with the var.
  1240. """
  1241. return self._var_data.state if self._var_data else ""
  1242. # Allow automatic serialization of Var within JSON structures
  1243. serializers.serializer(_encode_var)
  1244. @dataclasses.dataclass(
  1245. eq=False,
  1246. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1247. )
  1248. class BaseVar(Var):
  1249. """A base (non-computed) var of the app state."""
  1250. # The name of the var.
  1251. _var_name: str = dataclasses.field()
  1252. # The type of the var.
  1253. _var_type: Type = dataclasses.field(default=Any)
  1254. # Whether this is a local javascript variable.
  1255. _var_is_local: bool = dataclasses.field(default=False)
  1256. # Whether the var is a string literal.
  1257. _var_is_string: bool = dataclasses.field(default=False)
  1258. # _var_full_name should be prefixed with _var_state
  1259. _var_full_name_needs_state_prefix: bool = dataclasses.field(default=False)
  1260. # Extra metadata associated with the Var
  1261. _var_data: Optional[VarData] = dataclasses.field(default=None)
  1262. def __hash__(self) -> int:
  1263. """Define a hash function for a var.
  1264. Returns:
  1265. The hash of the var.
  1266. """
  1267. return hash((self._var_name, str(self._var_type)))
  1268. def get_default_value(self) -> Any:
  1269. """Get the default value of the var.
  1270. Returns:
  1271. The default value of the var.
  1272. Raises:
  1273. ImportError: If the var is a dataframe and pandas is not installed.
  1274. """
  1275. if types.is_optional(self._var_type):
  1276. return None
  1277. type_ = (
  1278. get_origin(self._var_type)
  1279. if types.is_generic_alias(self._var_type)
  1280. else self._var_type
  1281. )
  1282. if type_ is Literal:
  1283. args = get_args(self._var_type)
  1284. return args[0] if args else None
  1285. if issubclass(type_, str):
  1286. return ""
  1287. if issubclass(type_, types.get_args(Union[int, float])):
  1288. return 0
  1289. if issubclass(type_, bool):
  1290. return False
  1291. if issubclass(type_, list):
  1292. return []
  1293. if issubclass(type_, dict):
  1294. return {}
  1295. if issubclass(type_, tuple):
  1296. return ()
  1297. if types.is_dataframe(type_):
  1298. try:
  1299. import pandas as pd
  1300. return pd.DataFrame()
  1301. except ImportError as e:
  1302. raise ImportError(
  1303. "Please install pandas to use dataframes in your app."
  1304. ) from e
  1305. return set() if issubclass(type_, set) else None
  1306. def get_setter_name(self, include_state: bool = True) -> str:
  1307. """Get the name of the var's generated setter function.
  1308. Args:
  1309. include_state: Whether to include the state name in the setter name.
  1310. Returns:
  1311. The name of the setter function.
  1312. """
  1313. setter = constants.SETTER_PREFIX + self._var_name
  1314. if self._var_data is None:
  1315. return setter
  1316. if not include_state or self._var_data.state == "":
  1317. return setter
  1318. return ".".join((self._var_data.state, setter))
  1319. def get_setter(self) -> Callable[[BaseState, Any], None]:
  1320. """Get the var's setter function.
  1321. Returns:
  1322. A function that that creates a setter for the var.
  1323. """
  1324. def setter(state: BaseState, value: Any):
  1325. """Get the setter for the var.
  1326. Args:
  1327. state: The state within which we add the setter function.
  1328. value: The value to set.
  1329. """
  1330. if self._var_type in [int, float]:
  1331. try:
  1332. value = self._var_type(value)
  1333. setattr(state, self._var_name, value)
  1334. except ValueError:
  1335. console.warn(
  1336. f"{self._var_name}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
  1337. )
  1338. else:
  1339. setattr(state, self._var_name, value)
  1340. setter.__qualname__ = self.get_setter_name()
  1341. return setter
  1342. @dataclasses.dataclass(init=False, eq=False)
  1343. class ComputedVar(Var, property):
  1344. """A field with computed getters."""
  1345. # Whether to track dependencies and cache computed values
  1346. _cache: bool = dataclasses.field(default=False)
  1347. def __init__(
  1348. self,
  1349. fget: Callable[[BaseState], Any],
  1350. fset: Callable[[BaseState, Any], None] | None = None,
  1351. fdel: Callable[[BaseState], Any] | None = None,
  1352. doc: str | None = None,
  1353. **kwargs,
  1354. ):
  1355. """Initialize a ComputedVar.
  1356. Args:
  1357. fget: The getter function.
  1358. fset: The setter function.
  1359. fdel: The deleter function.
  1360. doc: The docstring.
  1361. **kwargs: additional attributes to set on the instance
  1362. """
  1363. property.__init__(self, fget, fset, fdel, doc)
  1364. kwargs["_var_name"] = kwargs.pop("_var_name", fget.__name__)
  1365. kwargs["_var_type"] = kwargs.pop("_var_type", self._determine_var_type())
  1366. BaseVar.__init__(self, **kwargs) # type: ignore
  1367. @property
  1368. def _cache_attr(self) -> str:
  1369. """Get the attribute used to cache the value on the instance.
  1370. Returns:
  1371. An attribute name.
  1372. """
  1373. return f"__cached_{self._var_name}"
  1374. def __get__(self, instance, owner):
  1375. """Get the ComputedVar value.
  1376. If the value is already cached on the instance, return the cached value.
  1377. Args:
  1378. instance: the instance of the class accessing this computed var.
  1379. owner: the class that this descriptor is attached to.
  1380. Returns:
  1381. The value of the var for the given instance.
  1382. """
  1383. if instance is None or not self._cache:
  1384. return super().__get__(instance, owner)
  1385. # handle caching
  1386. if not hasattr(instance, self._cache_attr):
  1387. setattr(instance, self._cache_attr, super().__get__(instance, owner))
  1388. return getattr(instance, self._cache_attr)
  1389. def _deps(
  1390. self,
  1391. objclass: Type,
  1392. obj: FunctionType | CodeType | None = None,
  1393. self_name: Optional[str] = None,
  1394. ) -> set[str]:
  1395. """Determine var dependencies of this ComputedVar.
  1396. Save references to attributes accessed on "self". Recursively called
  1397. when the function makes a method call on "self" or define comprehensions
  1398. or nested functions that may reference "self".
  1399. Args:
  1400. objclass: the class obj this ComputedVar is attached to.
  1401. obj: the object to disassemble (defaults to the fget function).
  1402. self_name: if specified, look for this name in LOAD_FAST and LOAD_DEREF instructions.
  1403. Returns:
  1404. A set of variable names accessed by the given obj.
  1405. """
  1406. d = set()
  1407. if obj is None:
  1408. if self.fget is not None:
  1409. obj = cast(FunctionType, self.fget)
  1410. else:
  1411. return set()
  1412. with contextlib.suppress(AttributeError):
  1413. # unbox functools.partial
  1414. obj = cast(FunctionType, obj.func) # type: ignore
  1415. with contextlib.suppress(AttributeError):
  1416. # unbox EventHandler
  1417. obj = cast(FunctionType, obj.fn) # type: ignore
  1418. if self_name is None and isinstance(obj, FunctionType):
  1419. try:
  1420. # the first argument to the function is the name of "self" arg
  1421. self_name = obj.__code__.co_varnames[0]
  1422. except (AttributeError, IndexError):
  1423. self_name = None
  1424. if self_name is None:
  1425. # cannot reference attributes on self if method takes no args
  1426. return set()
  1427. self_is_top_of_stack = False
  1428. for instruction in dis.get_instructions(obj):
  1429. if (
  1430. instruction.opname in ("LOAD_FAST", "LOAD_DEREF")
  1431. and instruction.argval == self_name
  1432. ):
  1433. # bytecode loaded the class instance to the top of stack, next load instruction
  1434. # is referencing an attribute on self
  1435. self_is_top_of_stack = True
  1436. continue
  1437. if self_is_top_of_stack and instruction.opname in (
  1438. "LOAD_ATTR",
  1439. "LOAD_METHOD",
  1440. ):
  1441. try:
  1442. ref_obj = getattr(objclass, instruction.argval)
  1443. except Exception:
  1444. ref_obj = None
  1445. if callable(ref_obj):
  1446. # recurse into callable attributes
  1447. d.update(
  1448. self._deps(
  1449. objclass=objclass,
  1450. obj=ref_obj,
  1451. )
  1452. )
  1453. else:
  1454. # normal attribute access
  1455. d.add(instruction.argval)
  1456. elif instruction.opname == "LOAD_CONST" and isinstance(
  1457. instruction.argval, CodeType
  1458. ):
  1459. # recurse into nested functions / comprehensions, which can reference
  1460. # instance attributes from the outer scope
  1461. d.update(
  1462. self._deps(
  1463. objclass=objclass,
  1464. obj=instruction.argval,
  1465. self_name=self_name,
  1466. )
  1467. )
  1468. self_is_top_of_stack = False
  1469. return d
  1470. def mark_dirty(self, instance) -> None:
  1471. """Mark this ComputedVar as dirty.
  1472. Args:
  1473. instance: the state instance that needs to recompute the value.
  1474. """
  1475. with contextlib.suppress(AttributeError):
  1476. delattr(instance, self._cache_attr)
  1477. def _determine_var_type(self) -> Type:
  1478. """Get the type of the var.
  1479. Returns:
  1480. The type of the var.
  1481. """
  1482. hints = get_type_hints(self.fget)
  1483. if "return" in hints:
  1484. return hints["return"]
  1485. return Any
  1486. def cached_var(fget: Callable[[Any], Any]) -> ComputedVar:
  1487. """A field with computed getter that tracks other state dependencies.
  1488. The cached_var will only be recalculated when other state vars that it
  1489. depends on are modified.
  1490. Args:
  1491. fget: the function that calculates the variable value.
  1492. Returns:
  1493. ComputedVar that is recomputed when dependencies change.
  1494. """
  1495. cvar = ComputedVar(fget=fget)
  1496. cvar._cache = True
  1497. return cvar
  1498. class CallableVar(BaseVar):
  1499. """Decorate a Var-returning function to act as both a Var and a function.
  1500. This is used as a compatibility shim for replacing Var objects in the
  1501. API with functions that return a family of Var.
  1502. """
  1503. def __init__(self, fn: Callable[..., BaseVar]):
  1504. """Initialize a CallableVar.
  1505. Args:
  1506. fn: The function to decorate (must return Var)
  1507. """
  1508. self.fn = fn
  1509. default_var = fn()
  1510. super().__init__(**dataclasses.asdict(default_var))
  1511. def __call__(self, *args, **kwargs) -> BaseVar:
  1512. """Call the decorated function.
  1513. Args:
  1514. *args: The args to pass to the function.
  1515. **kwargs: The kwargs to pass to the function.
  1516. Returns:
  1517. The Var returned from calling the function.
  1518. """
  1519. return self.fn(*args, **kwargs)