vars.py 76 KB

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