vars.py 75 KB

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