vars.py 74 KB

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