1
0

vars.py 73 KB

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