base.py 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443
  1. """Collection of base classes."""
  2. from __future__ import annotations
  3. import contextlib
  4. import copy
  5. import dataclasses
  6. import datetime
  7. import functools
  8. import inspect
  9. import json
  10. import random
  11. import re
  12. import string
  13. import uuid
  14. import warnings
  15. from collections.abc import Callable, Coroutine, Iterable, Mapping, Sequence
  16. from types import CodeType, FunctionType
  17. from typing import ( # noqa: UP035
  18. TYPE_CHECKING,
  19. Any,
  20. ClassVar,
  21. Dict,
  22. FrozenSet,
  23. Generic,
  24. List,
  25. Literal,
  26. NoReturn,
  27. ParamSpec,
  28. Protocol,
  29. Set,
  30. Tuple,
  31. TypeGuard,
  32. TypeVar,
  33. cast,
  34. get_args,
  35. get_type_hints,
  36. overload,
  37. )
  38. from rich.markup import escape
  39. from sqlalchemy.orm import DeclarativeBase
  40. from typing_extensions import deprecated, override
  41. from reflex import constants
  42. from reflex.base import Base
  43. from reflex.constants.compiler import Hooks
  44. from reflex.utils import console, exceptions, imports, serializers, types
  45. from reflex.utils.exceptions import (
  46. ComputedVarSignatureError,
  47. UntypedComputedVarError,
  48. VarAttributeError,
  49. VarDependencyError,
  50. VarTypeError,
  51. )
  52. from reflex.utils.format import format_state_name
  53. from reflex.utils.imports import (
  54. ImmutableImportDict,
  55. ImmutableParsedImportDict,
  56. ImportDict,
  57. ImportVar,
  58. ParsedImportTuple,
  59. parse_imports,
  60. )
  61. from reflex.utils.types import (
  62. GenericType,
  63. Self,
  64. _isinstance,
  65. get_origin,
  66. has_args,
  67. safe_issubclass,
  68. unionize,
  69. )
  70. if TYPE_CHECKING:
  71. from reflex.components.component import BaseComponent
  72. from reflex.state import BaseState
  73. from .number import BooleanVar, LiteralBooleanVar, LiteralNumberVar, NumberVar
  74. from .object import LiteralObjectVar, ObjectVar
  75. from .sequence import ArrayVar, LiteralArrayVar, LiteralStringVar, StringVar
  76. VAR_TYPE = TypeVar("VAR_TYPE", covariant=True)
  77. OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE")
  78. STRING_T = TypeVar("STRING_T", bound=str)
  79. SEQUENCE_TYPE = TypeVar("SEQUENCE_TYPE", bound=Sequence)
  80. warnings.filterwarnings("ignore", message="fields may not start with an underscore")
  81. @dataclasses.dataclass(
  82. eq=False,
  83. frozen=True,
  84. )
  85. class VarSubclassEntry:
  86. """Entry for a Var subclass."""
  87. var_subclass: type[Var]
  88. to_var_subclass: type[ToOperation]
  89. python_types: tuple[GenericType, ...]
  90. _var_subclasses: list[VarSubclassEntry] = []
  91. _var_literal_subclasses: list[tuple[type[LiteralVar], VarSubclassEntry]] = []
  92. @dataclasses.dataclass(
  93. eq=True,
  94. frozen=True,
  95. )
  96. class VarData:
  97. """Metadata associated with a x."""
  98. # The name of the enclosing state.
  99. state: str = dataclasses.field(default="")
  100. # The name of the field in the state.
  101. field_name: str = dataclasses.field(default="")
  102. # Imports needed to render this var
  103. imports: ParsedImportTuple = dataclasses.field(default_factory=tuple)
  104. # Hooks that need to be present in the component to render this var
  105. hooks: tuple[str, ...] = dataclasses.field(default_factory=tuple)
  106. # Dependencies of the var
  107. deps: tuple[Var, ...] = dataclasses.field(default_factory=tuple)
  108. # Position of the hook in the component
  109. position: Hooks.HookPosition | None = None
  110. # Components that are part of this var
  111. components: tuple[BaseComponent, ...] = dataclasses.field(default_factory=tuple)
  112. def __init__(
  113. self,
  114. state: str = "",
  115. field_name: str = "",
  116. imports: ImmutableImportDict | ImmutableParsedImportDict | None = None,
  117. hooks: Mapping[str, VarData | None] | Sequence[str] | str | None = None,
  118. deps: list[Var] | None = None,
  119. position: Hooks.HookPosition | None = None,
  120. components: Iterable[BaseComponent] | None = None,
  121. ):
  122. """Initialize the var data.
  123. Args:
  124. state: The name of the enclosing state.
  125. field_name: The name of the field in the state.
  126. imports: Imports needed to render this var.
  127. hooks: Hooks that need to be present in the component to render this var.
  128. deps: Dependencies of the var for useCallback.
  129. position: Position of the hook in the component.
  130. components: Components that are part of this var.
  131. """
  132. if isinstance(hooks, str):
  133. hooks = [hooks]
  134. if not isinstance(hooks, dict):
  135. hooks = dict.fromkeys(hooks or [])
  136. immutable_imports: ParsedImportTuple = tuple(
  137. (k, tuple(v)) for k, v in parse_imports(imports or {}).items()
  138. )
  139. object.__setattr__(self, "state", state)
  140. object.__setattr__(self, "field_name", field_name)
  141. object.__setattr__(self, "imports", immutable_imports)
  142. object.__setattr__(self, "hooks", tuple(hooks or {}))
  143. object.__setattr__(self, "deps", tuple(deps or []))
  144. object.__setattr__(self, "position", position or None)
  145. object.__setattr__(self, "components", tuple(components or []))
  146. if hooks and any(hooks.values()):
  147. merged_var_data = VarData.merge(self, *hooks.values())
  148. if merged_var_data is not None:
  149. object.__setattr__(self, "state", merged_var_data.state)
  150. object.__setattr__(self, "field_name", merged_var_data.field_name)
  151. object.__setattr__(self, "imports", merged_var_data.imports)
  152. object.__setattr__(self, "hooks", merged_var_data.hooks)
  153. object.__setattr__(self, "deps", merged_var_data.deps)
  154. object.__setattr__(self, "position", merged_var_data.position)
  155. object.__setattr__(self, "components", merged_var_data.components)
  156. def old_school_imports(self) -> ImportDict:
  157. """Return the imports as a mutable dict.
  158. Returns:
  159. The imports as a mutable dict.
  160. """
  161. return {k: list(v) for k, v in self.imports}
  162. def merge(*all: VarData | None) -> VarData | None:
  163. """Merge multiple var data objects.
  164. Args:
  165. *all: The var data objects to merge.
  166. Raises:
  167. ReflexError: If trying to merge VarData with different positions.
  168. Returns:
  169. The merged var data object.
  170. # noqa: DAR102 *all
  171. """
  172. all_var_datas = list(filter(None, all))
  173. if not all_var_datas:
  174. return None
  175. if len(all_var_datas) == 1:
  176. return all_var_datas[0]
  177. # Get the first non-empty field name or default to empty string.
  178. field_name = next(
  179. (var_data.field_name for var_data in all_var_datas if var_data.field_name),
  180. "",
  181. )
  182. # Get the first non-empty state or default to empty string.
  183. state = next(
  184. (var_data.state for var_data in all_var_datas if var_data.state), ""
  185. )
  186. hooks: dict[str, VarData | None] = {
  187. hook: None for var_data in all_var_datas for hook in var_data.hooks
  188. }
  189. _imports = imports.merge_imports(
  190. *(var_data.imports for var_data in all_var_datas)
  191. )
  192. deps = [dep for var_data in all_var_datas for dep in var_data.deps]
  193. positions = list(
  194. {
  195. var_data.position
  196. for var_data in all_var_datas
  197. if var_data.position is not None
  198. }
  199. )
  200. if positions:
  201. if len(positions) > 1:
  202. raise exceptions.ReflexError(
  203. f"Cannot merge var data with different positions: {positions}"
  204. )
  205. position = positions[0]
  206. else:
  207. position = None
  208. components = tuple(
  209. component for var_data in all_var_datas for component in var_data.components
  210. )
  211. return VarData(
  212. state=state,
  213. field_name=field_name,
  214. imports=_imports,
  215. hooks=hooks,
  216. deps=deps,
  217. position=position,
  218. components=components,
  219. )
  220. def __bool__(self) -> bool:
  221. """Check if the var data is non-empty.
  222. Returns:
  223. True if any field is set to a non-default value.
  224. """
  225. return bool(
  226. self.state
  227. or self.imports
  228. or self.hooks
  229. or self.field_name
  230. or self.deps
  231. or self.position
  232. or self.components
  233. )
  234. @classmethod
  235. def from_state(cls, state: type[BaseState] | str, field_name: str = "") -> VarData:
  236. """Set the state of the var.
  237. Args:
  238. state: The state to set or the full name of the state.
  239. field_name: The name of the field in the state. Optional.
  240. Returns:
  241. The var with the set state.
  242. """
  243. from reflex.utils import format
  244. state_name = state if isinstance(state, str) else state.get_full_name()
  245. return VarData(
  246. state=state_name,
  247. field_name=field_name,
  248. hooks={
  249. "const {0} = useContext(StateContexts.{0})".format(
  250. format.format_state_name(state_name)
  251. ): None
  252. },
  253. imports={
  254. f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  255. "react": [ImportVar(tag="useContext")],
  256. },
  257. )
  258. def _decode_var_immutable(value: str) -> tuple[VarData | None, str]:
  259. """Decode the state name from a formatted var.
  260. Args:
  261. value: The value to extract the state name from.
  262. Returns:
  263. The extracted state name and the value without the state name.
  264. """
  265. var_datas = []
  266. if isinstance(value, str):
  267. # fast path if there is no encoded VarData
  268. if constants.REFLEX_VAR_OPENING_TAG not in value:
  269. return None, value
  270. offset = 0
  271. # Find all tags.
  272. while m := _decode_var_pattern.search(value):
  273. start, end = m.span()
  274. value = value[:start] + value[end:]
  275. serialized_data = m.group(1)
  276. if serialized_data.isnumeric() or (
  277. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  278. ):
  279. # This is a global immutable var.
  280. var = _global_vars[int(serialized_data)]
  281. var_data = var._get_all_var_data()
  282. if var_data is not None:
  283. var_datas.append(var_data)
  284. offset += end - start
  285. return VarData.merge(*var_datas) if var_datas else None, value
  286. def can_use_in_object_var(cls: GenericType) -> bool:
  287. """Check if the class can be used in an ObjectVar.
  288. Args:
  289. cls: The class to check.
  290. Returns:
  291. Whether the class can be used in an ObjectVar.
  292. """
  293. if types.is_union(cls):
  294. return all(can_use_in_object_var(t) for t in types.get_args(cls))
  295. return (
  296. inspect.isclass(cls)
  297. and not safe_issubclass(cls, Var)
  298. and serializers.can_serialize(cls, dict)
  299. )
  300. @dataclasses.dataclass(
  301. eq=False,
  302. frozen=True,
  303. )
  304. class Var(Generic[VAR_TYPE]):
  305. """Base class for immutable vars."""
  306. # The name of the var.
  307. _js_expr: str = dataclasses.field()
  308. # The type of the var.
  309. _var_type: types.GenericType = dataclasses.field(default=Any)
  310. # Extra metadata associated with the Var
  311. _var_data: VarData | None = dataclasses.field(default=None)
  312. def __str__(self) -> str:
  313. """String representation of the var. Guaranteed to be a valid Javascript expression.
  314. Returns:
  315. The name of the var.
  316. """
  317. return self._js_expr
  318. @property
  319. def _var_is_local(self) -> bool:
  320. """Whether this is a local javascript variable.
  321. Returns:
  322. False
  323. """
  324. return False
  325. @property
  326. @deprecated("Use `_js_expr` instead.")
  327. def _var_name(self) -> str:
  328. """The name of the var.
  329. Returns:
  330. The name of the var.
  331. """
  332. return self._js_expr
  333. @property
  334. def _var_field_name(self) -> str:
  335. """The name of the field.
  336. Returns:
  337. The name of the field.
  338. """
  339. var_data = self._get_all_var_data()
  340. field_name = var_data.field_name if var_data else None
  341. return field_name or self._js_expr
  342. @property
  343. @deprecated("Use `_js_expr` instead.")
  344. def _var_name_unwrapped(self) -> str:
  345. """The name of the var without extra curly braces.
  346. Returns:
  347. The name of the var.
  348. """
  349. return self._js_expr
  350. @property
  351. def _var_is_string(self) -> bool:
  352. """Whether the var is a string literal.
  353. Returns:
  354. False
  355. """
  356. return False
  357. def __init_subclass__(
  358. cls,
  359. python_types: tuple[GenericType, ...] | GenericType = types.Unset(),
  360. default_type: GenericType = types.Unset(),
  361. **kwargs,
  362. ):
  363. """Initialize the subclass.
  364. Args:
  365. python_types: The python types that the var represents.
  366. default_type: The default type of the var. Defaults to the first python type.
  367. **kwargs: Additional keyword arguments.
  368. """
  369. super().__init_subclass__(**kwargs)
  370. if python_types or default_type:
  371. python_types = (
  372. (python_types if isinstance(python_types, tuple) else (python_types,))
  373. if python_types
  374. else ()
  375. )
  376. default_type = default_type or (python_types[0] if python_types else Any)
  377. @dataclasses.dataclass(
  378. eq=False,
  379. frozen=True,
  380. slots=True,
  381. )
  382. class ToVarOperation(ToOperation, cls):
  383. """Base class of converting a var to another var type."""
  384. _original: Var = dataclasses.field(
  385. default=Var(_js_expr="null", _var_type=None),
  386. )
  387. _default_var_type: ClassVar[GenericType] = default_type
  388. new_to_var_operation_name = f"{cls.__name__.removesuffix('Var')}CastedVar"
  389. ToVarOperation.__qualname__ = (
  390. ToVarOperation.__qualname__.removesuffix(ToVarOperation.__name__)
  391. + new_to_var_operation_name
  392. )
  393. ToVarOperation.__name__ = new_to_var_operation_name
  394. _var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types))
  395. def __post_init__(self):
  396. """Post-initialize the var.
  397. Raises:
  398. TypeError: If _js_expr is not a string.
  399. """
  400. if not isinstance(self._js_expr, str):
  401. raise TypeError(
  402. f"Expected _js_expr to be a string, got value {self._js_expr!r} of type {type(self._js_expr).__name__}"
  403. )
  404. if self._var_data is not None and not isinstance(self._var_data, VarData):
  405. raise TypeError(
  406. f"Expected _var_data to be a VarData, got value {self._var_data!r} of type {type(self._var_data).__name__}"
  407. )
  408. # Decode any inline Var markup and apply it to the instance
  409. _var_data, _js_expr = _decode_var_immutable(self._js_expr)
  410. if _var_data or _js_expr != self._js_expr:
  411. self.__init__(
  412. _js_expr=_js_expr,
  413. _var_type=self._var_type,
  414. _var_data=VarData.merge(self._var_data, _var_data),
  415. )
  416. def __hash__(self) -> int:
  417. """Define a hash function for the var.
  418. Returns:
  419. The hash of the var.
  420. """
  421. return hash((self._js_expr, self._var_type, self._var_data))
  422. def _get_all_var_data(self) -> VarData | None:
  423. """Get all VarData associated with the Var.
  424. Returns:
  425. The VarData of the components and all of its children.
  426. """
  427. return self._var_data
  428. def equals(self, other: Var) -> bool:
  429. """Check if two vars are equal.
  430. Args:
  431. other: The other var to compare.
  432. Returns:
  433. Whether the vars are equal.
  434. """
  435. return (
  436. self._js_expr == other._js_expr
  437. and self._var_type == other._var_type
  438. and self._get_all_var_data() == other._get_all_var_data()
  439. )
  440. @overload
  441. def _replace(
  442. self,
  443. _var_type: type[OTHER_VAR_TYPE],
  444. merge_var_data: VarData | None = None,
  445. **kwargs: Any,
  446. ) -> Var[OTHER_VAR_TYPE]: ...
  447. @overload
  448. def _replace(
  449. self,
  450. _var_type: GenericType | None = None,
  451. merge_var_data: VarData | None = None,
  452. **kwargs: Any,
  453. ) -> Self: ...
  454. def _replace(
  455. self,
  456. _var_type: GenericType | None = None,
  457. merge_var_data: VarData | None = None,
  458. **kwargs: Any,
  459. ) -> Self | Var:
  460. """Make a copy of this Var with updated fields.
  461. Args:
  462. _var_type: The new type of the Var.
  463. merge_var_data: VarData to merge into the existing VarData.
  464. **kwargs: Var fields to update.
  465. Returns:
  466. A new Var with the updated fields overwriting the corresponding fields in this Var.
  467. Raises:
  468. TypeError: If _var_is_local, _var_is_string, or _var_full_name_needs_state_prefix is not None.
  469. """
  470. if kwargs.get("_var_is_local", False) is not False:
  471. raise TypeError("The _var_is_local argument is not supported for Var.")
  472. if kwargs.get("_var_is_string", False) is not False:
  473. raise TypeError("The _var_is_string argument is not supported for Var.")
  474. if kwargs.get("_var_full_name_needs_state_prefix", False) is not False:
  475. raise TypeError(
  476. "The _var_full_name_needs_state_prefix argument is not supported for Var."
  477. )
  478. value_with_replaced = dataclasses.replace(
  479. self,
  480. _var_type=_var_type or self._var_type,
  481. _var_data=VarData.merge(
  482. kwargs.get("_var_data", self._var_data), merge_var_data
  483. ),
  484. **kwargs,
  485. )
  486. if (js_expr := kwargs.get("_js_expr")) is not None:
  487. object.__setattr__(value_with_replaced, "_js_expr", js_expr)
  488. return value_with_replaced
  489. @overload
  490. @classmethod
  491. def create( # pyright: ignore[reportOverlappingOverload]
  492. cls,
  493. value: NoReturn,
  494. _var_data: VarData | None = None,
  495. ) -> Var[Any]: ...
  496. @overload
  497. @classmethod
  498. def create( # pyright: ignore[reportOverlappingOverload]
  499. cls,
  500. value: bool,
  501. _var_data: VarData | None = None,
  502. ) -> LiteralBooleanVar: ...
  503. @overload
  504. @classmethod
  505. def create(
  506. cls,
  507. value: int,
  508. _var_data: VarData | None = None,
  509. ) -> LiteralNumberVar[int]: ...
  510. @overload
  511. @classmethod
  512. def create(
  513. cls,
  514. value: float,
  515. _var_data: VarData | None = None,
  516. ) -> LiteralNumberVar[float]: ...
  517. @overload
  518. @classmethod
  519. def create( # pyright: ignore [reportOverlappingOverload]
  520. cls,
  521. value: str,
  522. _var_data: VarData | None = None,
  523. ) -> LiteralStringVar: ...
  524. @overload
  525. @classmethod
  526. def create( # pyright: ignore [reportOverlappingOverload]
  527. cls,
  528. value: STRING_T,
  529. _var_data: VarData | None = None,
  530. ) -> StringVar[STRING_T]: ...
  531. @overload
  532. @classmethod
  533. def create( # pyright: ignore[reportOverlappingOverload]
  534. cls,
  535. value: None,
  536. _var_data: VarData | None = None,
  537. ) -> LiteralNoneVar: ...
  538. @overload
  539. @classmethod
  540. def create(
  541. cls,
  542. value: MAPPING_TYPE,
  543. _var_data: VarData | None = None,
  544. ) -> LiteralObjectVar[MAPPING_TYPE]: ...
  545. @overload
  546. @classmethod
  547. def create(
  548. cls,
  549. value: SEQUENCE_TYPE,
  550. _var_data: VarData | None = None,
  551. ) -> LiteralArrayVar[SEQUENCE_TYPE]: ...
  552. @overload
  553. @classmethod
  554. def create(
  555. cls,
  556. value: OTHER_VAR_TYPE,
  557. _var_data: VarData | None = None,
  558. ) -> Var[OTHER_VAR_TYPE]: ...
  559. @classmethod
  560. def create(
  561. cls,
  562. value: OTHER_VAR_TYPE,
  563. _var_data: VarData | None = None,
  564. ) -> Var[OTHER_VAR_TYPE]:
  565. """Create a var from a value.
  566. Args:
  567. value: The value to create the var from.
  568. _var_data: Additional hooks and imports associated with the Var.
  569. Returns:
  570. The var.
  571. """
  572. # If the value is already a var, do nothing.
  573. if isinstance(value, Var):
  574. return value
  575. return LiteralVar.create(value, _var_data=_var_data)
  576. @classmethod
  577. @deprecated("Use `.create()` instead.")
  578. def create_safe(
  579. cls,
  580. *args: Any,
  581. **kwargs: Any,
  582. ) -> Var:
  583. """Create a var from a value.
  584. Args:
  585. *args: The arguments to create the var from.
  586. **kwargs: The keyword arguments to create the var from.
  587. Returns:
  588. The var.
  589. """
  590. return cls.create(*args, **kwargs)
  591. def __format__(self, format_spec: str) -> str:
  592. """Format the var into a Javascript equivalent to an f-string.
  593. Args:
  594. format_spec: The format specifier (Ignored for now).
  595. Returns:
  596. The formatted var.
  597. """
  598. hashed_var = hash(self)
  599. _global_vars[hashed_var] = self
  600. # Encode the _var_data into the formatted output for tracking purposes.
  601. return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}"
  602. @overload
  603. def to(self, output: type[str]) -> StringVar: ...
  604. @overload
  605. def to(self, output: type[bool]) -> BooleanVar: ...
  606. @overload
  607. def to(self, output: type[int]) -> NumberVar[int]: ...
  608. @overload
  609. def to(self, output: type[int] | type[float]) -> NumberVar: ...
  610. @overload
  611. def to(
  612. self,
  613. output: type[list] | type[tuple] | type[set],
  614. ) -> ArrayVar: ...
  615. @overload
  616. def to(
  617. self,
  618. output: type[MAPPING_TYPE],
  619. ) -> ObjectVar[MAPPING_TYPE]: ...
  620. @overload
  621. def to(
  622. self, output: type[ObjectVar], var_type: type[VAR_INSIDE]
  623. ) -> ObjectVar[VAR_INSIDE]: ...
  624. @overload
  625. def to(
  626. self, output: type[ObjectVar], var_type: None = None
  627. ) -> ObjectVar[VAR_TYPE]: ...
  628. @overload
  629. def to(self, output: VAR_SUBCLASS, var_type: None = None) -> VAR_SUBCLASS: ...
  630. @overload
  631. def to(
  632. self,
  633. output: type[OUTPUT] | types.GenericType,
  634. var_type: types.GenericType | None = None,
  635. ) -> OUTPUT: ...
  636. def to(
  637. self,
  638. output: type[OUTPUT] | types.GenericType,
  639. var_type: types.GenericType | None = None,
  640. ) -> Var:
  641. """Convert the var to a different type.
  642. Args:
  643. output: The output type.
  644. var_type: The type of the var.
  645. Returns:
  646. The converted var.
  647. """
  648. from .object import ObjectVar
  649. fixed_output_type = get_origin(output) or output
  650. # If the first argument is a python type, we map it to the corresponding Var type.
  651. for var_subclass in _var_subclasses[::-1]:
  652. if fixed_output_type in var_subclass.python_types or safe_issubclass(
  653. fixed_output_type, var_subclass.python_types
  654. ):
  655. return self.to(var_subclass.var_subclass, output)
  656. if fixed_output_type is None:
  657. return get_to_operation(NoneVar).create(self) # pyright: ignore [reportReturnType]
  658. # Handle fixed_output_type being Base or a dataclass.
  659. if can_use_in_object_var(output):
  660. return self.to(ObjectVar, output)
  661. if inspect.isclass(output):
  662. for var_subclass in _var_subclasses[::-1]:
  663. if safe_issubclass(output, var_subclass.var_subclass):
  664. current_var_type = self._var_type
  665. if current_var_type is Any:
  666. new_var_type = var_type
  667. else:
  668. new_var_type = var_type or current_var_type
  669. to_operation_return = var_subclass.to_var_subclass.create(
  670. value=self, _var_type=new_var_type
  671. )
  672. return to_operation_return # pyright: ignore [reportReturnType]
  673. # If we can't determine the first argument, we just replace the _var_type.
  674. if not safe_issubclass(output, Var) or var_type is None:
  675. return dataclasses.replace(
  676. self,
  677. _var_type=output,
  678. )
  679. # We couldn't determine the output type to be any other Var type, so we replace the _var_type.
  680. if var_type is not None:
  681. return dataclasses.replace(
  682. self,
  683. _var_type=var_type,
  684. )
  685. return self
  686. @overload
  687. def guess_type(self: Var[NoReturn]) -> Var[Any]: ... # pyright: ignore [reportOverlappingOverload]
  688. @overload
  689. def guess_type(self: Var[str]) -> StringVar: ...
  690. @overload
  691. def guess_type(self: Var[bool]) -> BooleanVar: ...
  692. @overload
  693. def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ...
  694. @overload
  695. def guess_type(self: Var[BASE_TYPE]) -> ObjectVar[BASE_TYPE]: ...
  696. @overload
  697. def guess_type(self) -> Self: ...
  698. def guess_type(self) -> Var:
  699. """Guesses the type of the variable based on its `_var_type` attribute.
  700. Returns:
  701. Var: The guessed type of the variable.
  702. Raises:
  703. TypeError: If the type is not supported for guessing.
  704. """
  705. from .object import ObjectVar
  706. var_type = self._var_type
  707. if var_type is None:
  708. return self.to(None)
  709. if var_type is NoReturn:
  710. return self.to(Any)
  711. var_type = types.value_inside_optional(var_type)
  712. if var_type is Any:
  713. return self
  714. fixed_type = get_origin(var_type) or var_type
  715. if fixed_type in types.UnionTypes:
  716. inner_types = get_args(var_type)
  717. non_optional_inner_types = [
  718. types.value_inside_optional(inner_type) for inner_type in inner_types
  719. ]
  720. fixed_inner_types = [
  721. get_origin(inner_type) or inner_type
  722. for inner_type in non_optional_inner_types
  723. ]
  724. for var_subclass in _var_subclasses[::-1]:
  725. if all(
  726. safe_issubclass(t, var_subclass.python_types)
  727. for t in fixed_inner_types
  728. ):
  729. return self.to(var_subclass.var_subclass, self._var_type)
  730. if can_use_in_object_var(var_type):
  731. return self.to(ObjectVar, self._var_type)
  732. return self
  733. if fixed_type is Literal:
  734. args = get_args(var_type)
  735. fixed_type = unionize(*(type(arg) for arg in args))
  736. if not inspect.isclass(fixed_type):
  737. raise TypeError(f"Unsupported type {var_type} for guess_type.")
  738. if fixed_type is None:
  739. return self.to(None)
  740. for var_subclass in _var_subclasses[::-1]:
  741. if safe_issubclass(fixed_type, var_subclass.python_types):
  742. return self.to(var_subclass.var_subclass, self._var_type)
  743. if can_use_in_object_var(fixed_type):
  744. return self.to(ObjectVar, self._var_type)
  745. return self
  746. def _get_default_value(self) -> Any:
  747. """Get the default value of the var.
  748. Returns:
  749. The default value of the var.
  750. Raises:
  751. ImportError: If the var is a dataframe and pandas is not installed.
  752. """
  753. if types.is_optional(self._var_type):
  754. return None
  755. type_ = (
  756. get_origin(self._var_type)
  757. if types.is_generic_alias(self._var_type)
  758. else self._var_type
  759. )
  760. if type_ is Literal:
  761. args = get_args(self._var_type)
  762. return args[0] if args else None
  763. if safe_issubclass(type_, str):
  764. return ""
  765. if safe_issubclass(type_, types.get_args(int | float)):
  766. return 0
  767. if safe_issubclass(type_, bool):
  768. return False
  769. if safe_issubclass(type_, list):
  770. return []
  771. if safe_issubclass(type_, Mapping):
  772. return {}
  773. if safe_issubclass(type_, tuple):
  774. return ()
  775. if types.is_dataframe(type_):
  776. try:
  777. import pandas as pd
  778. return pd.DataFrame()
  779. except ImportError as e:
  780. raise ImportError(
  781. "Please install pandas to use dataframes in your app."
  782. ) from e
  783. return set() if safe_issubclass(type_, set) else None
  784. def _get_setter_name(self, include_state: bool = True) -> str:
  785. """Get the name of the var's generated setter function.
  786. Args:
  787. include_state: Whether to include the state name in the setter name.
  788. Returns:
  789. The name of the setter function.
  790. """
  791. setter = constants.SETTER_PREFIX + self._var_field_name
  792. var_data = self._get_all_var_data()
  793. if var_data is None:
  794. return setter
  795. if not include_state or var_data.state == "":
  796. return setter
  797. return ".".join((var_data.state, setter))
  798. def _get_setter(self) -> Callable[[BaseState, Any], None]:
  799. """Get the var's setter function.
  800. Returns:
  801. A function that that creates a setter for the var.
  802. """
  803. actual_name = self._var_field_name
  804. def setter(state: Any, value: Any):
  805. """Get the setter for the var.
  806. Args:
  807. state: The state within which we add the setter function.
  808. value: The value to set.
  809. """
  810. if self._var_type in [int, float]:
  811. try:
  812. value = self._var_type(value)
  813. setattr(state, actual_name, value)
  814. except ValueError:
  815. console.debug(
  816. f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value!s} to '{self._var_type.__name__}'. Value not set.",
  817. )
  818. else:
  819. setattr(state, actual_name, value)
  820. setter.__annotations__["value"] = self._var_type
  821. setter.__qualname__ = self._get_setter_name()
  822. return setter
  823. def _var_set_state(self, state: type[BaseState] | str) -> Self:
  824. """Set the state of the var.
  825. Args:
  826. state: The state to set.
  827. Returns:
  828. The var with the state set.
  829. """
  830. formatted_state_name = (
  831. state
  832. if isinstance(state, str)
  833. else format_state_name(state.get_full_name())
  834. )
  835. return StateOperation.create( # pyright: ignore [reportReturnType]
  836. formatted_state_name,
  837. self,
  838. _var_data=VarData.merge(
  839. VarData.from_state(state, self._js_expr), self._var_data
  840. ),
  841. ).guess_type()
  842. def __eq__(self, other: Var | Any) -> BooleanVar:
  843. """Check if the current variable is equal to the given variable.
  844. Args:
  845. other (Var | Any): The variable to compare with.
  846. Returns:
  847. BooleanVar: A BooleanVar object representing the result of the equality check.
  848. """
  849. from .number import equal_operation
  850. return equal_operation(self, other)
  851. def __ne__(self, other: Var | Any) -> BooleanVar:
  852. """Check if the current object is not equal to the given object.
  853. Parameters:
  854. other (Var | Any): The object to compare with.
  855. Returns:
  856. BooleanVar: A BooleanVar object representing the result of the comparison.
  857. """
  858. from .number import equal_operation
  859. return ~equal_operation(self, other)
  860. def bool(self) -> BooleanVar:
  861. """Convert the var to a boolean.
  862. Returns:
  863. The boolean var.
  864. """
  865. from .number import boolify
  866. return boolify(self)
  867. def is_none(self) -> BooleanVar:
  868. """Check if the var is None.
  869. Returns:
  870. A BooleanVar object representing the result of the check.
  871. """
  872. from .number import is_not_none_operation
  873. return ~is_not_none_operation(self)
  874. def is_not_none(self) -> BooleanVar:
  875. """Check if the var is not None.
  876. Returns:
  877. A BooleanVar object representing the result of the check.
  878. """
  879. from .number import is_not_none_operation
  880. return is_not_none_operation(self)
  881. def __and__(
  882. self, other: Var[OTHER_VAR_TYPE] | Any
  883. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  884. """Perform a logical AND operation on the current instance and another variable.
  885. Args:
  886. other: The variable to perform the logical AND operation with.
  887. Returns:
  888. A `BooleanVar` object representing the result of the logical AND operation.
  889. """
  890. return and_operation(self, other)
  891. def __rand__(
  892. self, other: Var[OTHER_VAR_TYPE] | Any
  893. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  894. """Perform a logical AND operation on the current instance and another variable.
  895. Args:
  896. other: The variable to perform the logical AND operation with.
  897. Returns:
  898. A `BooleanVar` object representing the result of the logical AND operation.
  899. """
  900. return and_operation(other, self)
  901. def __or__(
  902. self, other: Var[OTHER_VAR_TYPE] | Any
  903. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  904. """Perform a logical OR operation on the current instance and another variable.
  905. Args:
  906. other: The variable to perform the logical OR operation with.
  907. Returns:
  908. A `BooleanVar` object representing the result of the logical OR operation.
  909. """
  910. return or_operation(self, other)
  911. def __ror__(
  912. self, other: Var[OTHER_VAR_TYPE] | Any
  913. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  914. """Perform a logical OR operation on the current instance and another variable.
  915. Args:
  916. other: The variable to perform the logical OR operation with.
  917. Returns:
  918. A `BooleanVar` object representing the result of the logical OR operation.
  919. """
  920. return or_operation(other, self)
  921. def __invert__(self) -> BooleanVar:
  922. """Perform a logical NOT operation on the current instance.
  923. Returns:
  924. A `BooleanVar` object representing the result of the logical NOT operation.
  925. """
  926. return ~self.bool()
  927. def to_string(self, use_json: bool = True) -> StringVar:
  928. """Convert the var to a string.
  929. Args:
  930. use_json: Whether to use JSON stringify. If False, uses Object.prototype.toString.
  931. Returns:
  932. The string var.
  933. """
  934. from .function import JSON_STRINGIFY, PROTOTYPE_TO_STRING
  935. from .sequence import StringVar
  936. return (
  937. JSON_STRINGIFY.call(self).to(StringVar)
  938. if use_json
  939. else PROTOTYPE_TO_STRING.call(self).to(StringVar)
  940. )
  941. def _as_ref(self) -> Var:
  942. """Get a reference to the var.
  943. Returns:
  944. The reference to the var.
  945. """
  946. from .object import ObjectVar
  947. refs = Var(
  948. _js_expr="refs",
  949. _var_data=VarData(
  950. imports={
  951. f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
  952. }
  953. ),
  954. ).to(ObjectVar, Mapping[str, str])
  955. return refs[LiteralVar.create(str(self))]
  956. @deprecated("Use `.js_type()` instead.")
  957. def _type(self) -> StringVar:
  958. """Returns the type of the object.
  959. This method uses the `typeof` function from the `FunctionStringVar` class
  960. to determine the type of the object.
  961. Returns:
  962. StringVar: A string variable representing the type of the object.
  963. """
  964. return self.js_type()
  965. def js_type(self) -> StringVar:
  966. """Returns the javascript type of the object.
  967. This method uses the `typeof` function from the `FunctionStringVar` class
  968. to determine the type of the object.
  969. Returns:
  970. StringVar: A string variable representing the type of the object.
  971. """
  972. from .function import FunctionStringVar
  973. from .sequence import StringVar
  974. type_of = FunctionStringVar("typeof")
  975. return type_of.call(self).to(StringVar)
  976. def _without_data(self):
  977. """Create a copy of the var without the data.
  978. Returns:
  979. The var without the data.
  980. """
  981. return dataclasses.replace(self, _var_data=None)
  982. def __get__(self, instance: Any, owner: Any):
  983. """Get the var.
  984. Args:
  985. instance: The instance to get the var from.
  986. owner: The owner of the var.
  987. Returns:
  988. The var.
  989. """
  990. return self
  991. def _decode(self) -> Any:
  992. """Decode Var as a python value.
  993. Note that Var with state set cannot be decoded python-side and will be
  994. returned as full_name.
  995. Returns:
  996. The decoded value or the Var name.
  997. """
  998. if isinstance(self, LiteralVar):
  999. return self._var_value
  1000. try:
  1001. return json.loads(str(self))
  1002. except ValueError:
  1003. return str(self)
  1004. @property
  1005. def _var_state(self) -> str:
  1006. """Compat method for getting the state.
  1007. Returns:
  1008. The state name associated with the var.
  1009. """
  1010. var_data = self._get_all_var_data()
  1011. return var_data.state if var_data else ""
  1012. @overload
  1013. @classmethod
  1014. def range(cls, stop: int | NumberVar, /) -> ArrayVar[Sequence[int]]: ...
  1015. @overload
  1016. @classmethod
  1017. def range(
  1018. cls,
  1019. start: int | NumberVar,
  1020. end: int | NumberVar,
  1021. step: int | NumberVar = 1,
  1022. /,
  1023. ) -> ArrayVar[Sequence[int]]: ...
  1024. @classmethod
  1025. def range(
  1026. cls,
  1027. first_endpoint: int | NumberVar,
  1028. second_endpoint: int | NumberVar | None = None,
  1029. step: int | NumberVar | None = None,
  1030. ) -> ArrayVar[Sequence[int]]:
  1031. """Create a range of numbers.
  1032. Args:
  1033. first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
  1034. second_endpoint: The end of the range.
  1035. step: The step of the range.
  1036. Returns:
  1037. The range of numbers.
  1038. """
  1039. from .sequence import ArrayVar
  1040. return ArrayVar.range(first_endpoint, second_endpoint, step)
  1041. if not TYPE_CHECKING:
  1042. def __getitem__(self, key: Any) -> Var:
  1043. """Get the item from the var.
  1044. Args:
  1045. key: The key to get.
  1046. Raises:
  1047. UntypedVarError: If the var type is Any.
  1048. TypeError: If the var type is Any.
  1049. # noqa: DAR101 self
  1050. """
  1051. if self._var_type is Any:
  1052. raise exceptions.UntypedVarError(
  1053. self,
  1054. f"access the item '{key}'",
  1055. )
  1056. raise TypeError(
  1057. f"Var of type {self._var_type} does not support item access."
  1058. )
  1059. def __getattr__(self, name: str):
  1060. """Get an attribute of the var.
  1061. Args:
  1062. name: The name of the attribute.
  1063. Raises:
  1064. VarAttributeError: If the attribute does not exist.
  1065. UntypedVarError: If the var type is Any.
  1066. TypeError: If the var type is Any.
  1067. # noqa: DAR101 self
  1068. """
  1069. if name.startswith("_"):
  1070. raise VarAttributeError(f"Attribute {name} not found.")
  1071. if name == "contains":
  1072. raise TypeError(
  1073. f"Var of type {self._var_type} does not support contains check."
  1074. )
  1075. if name == "reverse":
  1076. raise TypeError("Cannot reverse non-list var.")
  1077. if self._var_type is Any:
  1078. raise exceptions.UntypedVarError(
  1079. self,
  1080. f"access the attribute '{name}'",
  1081. )
  1082. raise VarAttributeError(
  1083. f"The State var {escape(self._js_expr)} of type {escape(str(self._var_type))} has no attribute '{name}' or may have been annotated wrongly.",
  1084. )
  1085. def __bool__(self) -> bool:
  1086. """Raise exception if using Var in a boolean context.
  1087. Raises:
  1088. VarTypeError: when attempting to bool-ify the Var.
  1089. # noqa: DAR101 self
  1090. """
  1091. raise VarTypeError(
  1092. f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. "
  1093. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  1094. )
  1095. def __iter__(self) -> Any:
  1096. """Raise exception if using Var in an iterable context.
  1097. Raises:
  1098. VarTypeError: when attempting to iterate over the Var.
  1099. # noqa: DAR101 self
  1100. """
  1101. raise VarTypeError(
  1102. f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`."
  1103. )
  1104. def __contains__(self, _: Any) -> Var:
  1105. """Override the 'in' operator to alert the user that it is not supported.
  1106. Raises:
  1107. VarTypeError: the operation is not supported
  1108. # noqa: DAR101 self
  1109. """
  1110. raise VarTypeError(
  1111. "'in' operator not supported for Var types, use Var.contains() instead."
  1112. )
  1113. OUTPUT = TypeVar("OUTPUT", bound=Var)
  1114. VAR_SUBCLASS = TypeVar("VAR_SUBCLASS", bound=Var)
  1115. VAR_INSIDE = TypeVar("VAR_INSIDE")
  1116. class ToOperation:
  1117. """A var operation that converts a var to another type."""
  1118. def __getattr__(self, name: str) -> Any:
  1119. """Get an attribute of the var.
  1120. Args:
  1121. name: The name of the attribute.
  1122. Returns:
  1123. The attribute of the var.
  1124. """
  1125. from .object import ObjectVar
  1126. if isinstance(self, ObjectVar) and name != "_js_expr":
  1127. return ObjectVar.__getattr__(self, name)
  1128. return getattr(self._original, name)
  1129. def __post_init__(self):
  1130. """Post initialization."""
  1131. object.__delattr__(self, "_js_expr")
  1132. def __hash__(self) -> int:
  1133. """Calculate the hash value of the object.
  1134. Returns:
  1135. int: The hash value of the object.
  1136. """
  1137. return hash(self._original)
  1138. def _get_all_var_data(self) -> VarData | None:
  1139. """Get all the var data.
  1140. Returns:
  1141. The var data.
  1142. """
  1143. return VarData.merge(
  1144. self._original._get_all_var_data(),
  1145. self._var_data,
  1146. )
  1147. @classmethod
  1148. def create(
  1149. cls,
  1150. value: Var,
  1151. _var_type: GenericType | None = None,
  1152. _var_data: VarData | None = None,
  1153. ):
  1154. """Create a ToOperation.
  1155. Args:
  1156. value: The value of the var.
  1157. _var_type: The type of the Var.
  1158. _var_data: Additional hooks and imports associated with the Var.
  1159. Returns:
  1160. The ToOperation.
  1161. """
  1162. return cls(
  1163. _js_expr="", # pyright: ignore [reportCallIssue]
  1164. _var_data=_var_data, # pyright: ignore [reportCallIssue]
  1165. _var_type=_var_type or cls._default_var_type, # pyright: ignore [reportCallIssue, reportAttributeAccessIssue]
  1166. _original=value, # pyright: ignore [reportCallIssue]
  1167. )
  1168. class LiteralVar(Var):
  1169. """Base class for immutable literal vars."""
  1170. def __init_subclass__(cls, **kwargs):
  1171. """Initialize the subclass.
  1172. Args:
  1173. **kwargs: Additional keyword arguments.
  1174. Raises:
  1175. TypeError: If the LiteralVar subclass does not have a corresponding Var subclass.
  1176. """
  1177. super().__init_subclass__(**kwargs)
  1178. bases = cls.__bases__
  1179. bases_normalized = [
  1180. base if inspect.isclass(base) else get_origin(base) for base in bases
  1181. ]
  1182. possible_bases = [
  1183. base
  1184. for base in bases_normalized
  1185. if safe_issubclass(base, Var) and base != LiteralVar
  1186. ]
  1187. if not possible_bases:
  1188. raise TypeError(
  1189. f"LiteralVar subclass {cls} must have a base class that is a subclass of Var and not LiteralVar."
  1190. )
  1191. var_subclasses = [
  1192. var_subclass
  1193. for var_subclass in _var_subclasses
  1194. if var_subclass.var_subclass in possible_bases
  1195. ]
  1196. if not var_subclasses:
  1197. raise TypeError(
  1198. f"LiteralVar {cls} must have a base class annotated with `python_types`."
  1199. )
  1200. if len(var_subclasses) != 1:
  1201. raise TypeError(
  1202. f"LiteralVar {cls} must have exactly one base class annotated with `python_types`."
  1203. )
  1204. var_subclass = var_subclasses[0]
  1205. # Remove the old subclass, happens because __init_subclass__ is called twice
  1206. # for each subclass. This is because of __slots__ in dataclasses.
  1207. for var_literal_subclass in list(_var_literal_subclasses):
  1208. if var_literal_subclass[1] is var_subclass:
  1209. _var_literal_subclasses.remove(var_literal_subclass)
  1210. _var_literal_subclasses.append((cls, var_subclass))
  1211. @classmethod
  1212. def _create_literal_var(
  1213. cls,
  1214. value: Any,
  1215. _var_data: VarData | None = None,
  1216. ) -> Var:
  1217. """Create a var from a value.
  1218. Args:
  1219. value: The value to create the var from.
  1220. _var_data: Additional hooks and imports associated with the Var.
  1221. Returns:
  1222. The var.
  1223. Raises:
  1224. TypeError: If the value is not a supported type for LiteralVar.
  1225. """
  1226. from .object import LiteralObjectVar
  1227. from .sequence import ArrayVar, LiteralStringVar
  1228. if isinstance(value, Var):
  1229. if _var_data is None:
  1230. return value
  1231. return value._replace(merge_var_data=_var_data)
  1232. for literal_subclass, var_subclass in _var_literal_subclasses[::-1]:
  1233. if isinstance(value, var_subclass.python_types):
  1234. return literal_subclass.create(value, _var_data=_var_data)
  1235. from reflex.event import EventHandler
  1236. from reflex.utils.format import get_event_handler_parts
  1237. if isinstance(value, EventHandler):
  1238. return Var(_js_expr=".".join(filter(None, get_event_handler_parts(value))))
  1239. serialized_value = serializers.serialize(value)
  1240. if serialized_value is not None:
  1241. if isinstance(serialized_value, Mapping):
  1242. return LiteralObjectVar.create(
  1243. serialized_value,
  1244. _var_type=type(value),
  1245. _var_data=_var_data,
  1246. )
  1247. if isinstance(serialized_value, str):
  1248. return LiteralStringVar.create(
  1249. serialized_value, _var_type=type(value), _var_data=_var_data
  1250. )
  1251. return LiteralVar.create(serialized_value, _var_data=_var_data)
  1252. if isinstance(value, Base):
  1253. # get the fields of the pydantic class
  1254. fields = value.__fields__.keys()
  1255. one_level_dict = {field: getattr(value, field) for field in fields}
  1256. return LiteralObjectVar.create(
  1257. {
  1258. field: value
  1259. for field, value in one_level_dict.items()
  1260. if not callable(value)
  1261. },
  1262. _var_type=type(value),
  1263. _var_data=_var_data,
  1264. )
  1265. if dataclasses.is_dataclass(value) and not isinstance(value, type):
  1266. return LiteralObjectVar.create(
  1267. {
  1268. k: (None if callable(v) else v)
  1269. for k, v in dataclasses.asdict(value).items()
  1270. },
  1271. _var_type=type(value),
  1272. _var_data=_var_data,
  1273. )
  1274. if isinstance(value, range):
  1275. return ArrayVar.range(value.start, value.stop, value.step)
  1276. raise TypeError(
  1277. f"Unsupported type {type(value)} for LiteralVar. Tried to create a LiteralVar from {value}."
  1278. )
  1279. if not TYPE_CHECKING:
  1280. create = _create_literal_var
  1281. def __post_init__(self):
  1282. """Post-initialize the var."""
  1283. @property
  1284. def _var_value(self) -> Any:
  1285. raise NotImplementedError(
  1286. "LiteralVar subclasses must implement the _var_value property."
  1287. )
  1288. def json(self) -> str:
  1289. """Serialize the var to a JSON string.
  1290. Raises:
  1291. NotImplementedError: If the method is not implemented.
  1292. """
  1293. raise NotImplementedError(
  1294. "LiteralVar subclasses must implement the json method."
  1295. )
  1296. @serializers.serializer
  1297. def serialize_literal(value: LiteralVar):
  1298. """Serialize a Literal type.
  1299. Args:
  1300. value: The Literal to serialize.
  1301. Returns:
  1302. The serialized Literal.
  1303. """
  1304. return value._var_value
  1305. def get_python_literal(value: LiteralVar | Any) -> Any | None:
  1306. """Get the Python literal value.
  1307. Args:
  1308. value: The value to get the Python literal value of.
  1309. Returns:
  1310. The Python literal value.
  1311. """
  1312. if isinstance(value, LiteralVar):
  1313. return value._var_value
  1314. if isinstance(value, Var):
  1315. return None
  1316. return value
  1317. P = ParamSpec("P")
  1318. T = TypeVar("T")
  1319. # NoReturn is used to match CustomVarOperationReturn with no type hint.
  1320. @overload
  1321. def var_operation( # pyright: ignore [reportOverlappingOverload]
  1322. func: Callable[P, CustomVarOperationReturn[NoReturn]],
  1323. ) -> Callable[P, Var]: ...
  1324. @overload
  1325. def var_operation(
  1326. func: Callable[P, CustomVarOperationReturn[None]],
  1327. ) -> Callable[P, NoneVar]: ...
  1328. @overload
  1329. def var_operation( # pyright: ignore [reportOverlappingOverload]
  1330. func: Callable[P, CustomVarOperationReturn[bool]]
  1331. | Callable[P, CustomVarOperationReturn[bool | None]],
  1332. ) -> Callable[P, BooleanVar]: ...
  1333. NUMBER_T = TypeVar("NUMBER_T", int, float, int | float)
  1334. @overload
  1335. def var_operation(
  1336. func: Callable[P, CustomVarOperationReturn[NUMBER_T]]
  1337. | Callable[P, CustomVarOperationReturn[NUMBER_T | None]],
  1338. ) -> Callable[P, NumberVar[NUMBER_T]]: ...
  1339. @overload
  1340. def var_operation(
  1341. func: Callable[P, CustomVarOperationReturn[str]]
  1342. | Callable[P, CustomVarOperationReturn[str | None]],
  1343. ) -> Callable[P, StringVar]: ...
  1344. LIST_T = TypeVar("LIST_T", bound=Sequence)
  1345. @overload
  1346. def var_operation(
  1347. func: Callable[P, CustomVarOperationReturn[LIST_T]]
  1348. | Callable[P, CustomVarOperationReturn[LIST_T | None]],
  1349. ) -> Callable[P, ArrayVar[LIST_T]]: ...
  1350. OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Mapping)
  1351. @overload
  1352. def var_operation(
  1353. func: Callable[P, CustomVarOperationReturn[OBJECT_TYPE]]
  1354. | Callable[P, CustomVarOperationReturn[OBJECT_TYPE | None]],
  1355. ) -> Callable[P, ObjectVar[OBJECT_TYPE]]: ...
  1356. @overload
  1357. def var_operation(
  1358. func: Callable[P, CustomVarOperationReturn[T]]
  1359. | Callable[P, CustomVarOperationReturn[T | None]],
  1360. ) -> Callable[P, Var[T]]: ...
  1361. def var_operation( # pyright: ignore [reportInconsistentOverload]
  1362. func: Callable[P, CustomVarOperationReturn[T]],
  1363. ) -> Callable[P, Var[T]]:
  1364. """Decorator for creating a var operation.
  1365. Example:
  1366. ```python
  1367. @var_operation
  1368. def add(a: NumberVar, b: NumberVar):
  1369. return custom_var_operation(f"{a} + {b}")
  1370. ```
  1371. Args:
  1372. func: The function to decorate.
  1373. Returns:
  1374. The decorated function.
  1375. """
  1376. @functools.wraps(func)
  1377. def wrapper(*args: P.args, **kwargs: P.kwargs) -> Var[T]:
  1378. func_args = list(inspect.signature(func).parameters)
  1379. args_vars = {
  1380. func_args[i]: (LiteralVar.create(arg) if not isinstance(arg, Var) else arg)
  1381. for i, arg in enumerate(args)
  1382. }
  1383. kwargs_vars = {
  1384. key: LiteralVar.create(value) if not isinstance(value, Var) else value
  1385. for key, value in kwargs.items()
  1386. }
  1387. return CustomVarOperation.create(
  1388. name=func.__name__,
  1389. args=tuple(list(args_vars.items()) + list(kwargs_vars.items())),
  1390. return_var=func(*args_vars.values(), **kwargs_vars), # pyright: ignore [reportCallIssue, reportReturnType]
  1391. ).guess_type()
  1392. return wrapper
  1393. def figure_out_type(value: Any) -> types.GenericType:
  1394. """Figure out the type of the value.
  1395. Args:
  1396. value: The value to figure out the type of.
  1397. Returns:
  1398. The type of the value.
  1399. """
  1400. if isinstance(value, Var):
  1401. return value._var_type
  1402. type_ = type(value)
  1403. if has_args(type_):
  1404. return type_
  1405. if isinstance(value, list):
  1406. if not value:
  1407. return Sequence[NoReturn]
  1408. return Sequence[unionize(*(figure_out_type(v) for v in value))]
  1409. if isinstance(value, set):
  1410. return set[unionize(*(figure_out_type(v) for v in value))]
  1411. if isinstance(value, tuple):
  1412. if not value:
  1413. return tuple[NoReturn, ...]
  1414. if len(value) <= 5:
  1415. return tuple[tuple(figure_out_type(v) for v in value)]
  1416. return tuple[unionize(*(figure_out_type(v) for v in value)), ...]
  1417. if isinstance(value, Mapping):
  1418. if not value:
  1419. return Mapping[NoReturn, NoReturn]
  1420. return Mapping[
  1421. unionize(*(figure_out_type(k) for k in value)),
  1422. unionize(*(figure_out_type(v) for v in value.values())),
  1423. ]
  1424. return type(value)
  1425. GLOBAL_CACHE = {}
  1426. class cached_property: # noqa: N801
  1427. """A cached property that caches the result of the function."""
  1428. def __init__(self, func: Callable):
  1429. """Initialize the cached_property.
  1430. Args:
  1431. func: The function to cache.
  1432. """
  1433. self._func = func
  1434. self._attrname = None
  1435. def __set_name__(self, owner: Any, name: str):
  1436. """Set the name of the cached property.
  1437. Args:
  1438. owner: The owner of the cached property.
  1439. name: The name of the cached property.
  1440. Raises:
  1441. TypeError: If the cached property is assigned to two different names.
  1442. """
  1443. if self._attrname is None:
  1444. self._attrname = name
  1445. original_del = getattr(owner, "__del__", None)
  1446. def delete_property(this: Any):
  1447. """Delete the cached property.
  1448. Args:
  1449. this: The object to delete the cached property from.
  1450. """
  1451. cached_field_name = "_reflex_cache_" + name
  1452. try:
  1453. unique_id = object.__getattribute__(this, cached_field_name)
  1454. except AttributeError:
  1455. if original_del is not None:
  1456. original_del(this)
  1457. return
  1458. GLOBAL_CACHE.pop(unique_id, None)
  1459. if original_del is not None:
  1460. original_del(this)
  1461. owner.__del__ = delete_property
  1462. elif name != self._attrname:
  1463. raise TypeError(
  1464. "Cannot assign the same cached_property to two different names "
  1465. f"({self._attrname!r} and {name!r})."
  1466. )
  1467. def __get__(self, instance: Any, owner: type | None = None):
  1468. """Get the cached property.
  1469. Args:
  1470. instance: The instance to get the cached property from.
  1471. owner: The owner of the cached property.
  1472. Returns:
  1473. The cached property.
  1474. Raises:
  1475. TypeError: If the class does not have __set_name__.
  1476. """
  1477. if self._attrname is None:
  1478. raise TypeError(
  1479. "Cannot use cached_property on a class without __set_name__."
  1480. )
  1481. cached_field_name = "_reflex_cache_" + self._attrname
  1482. try:
  1483. unique_id = object.__getattribute__(instance, cached_field_name)
  1484. except AttributeError:
  1485. unique_id = uuid.uuid4().int
  1486. object.__setattr__(instance, cached_field_name, unique_id)
  1487. if unique_id not in GLOBAL_CACHE:
  1488. GLOBAL_CACHE[unique_id] = self._func(instance)
  1489. return GLOBAL_CACHE[unique_id]
  1490. cached_property_no_lock = cached_property
  1491. class VarProtocol(Protocol):
  1492. """A protocol for Var."""
  1493. __dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]
  1494. @property
  1495. def _js_expr(self) -> str: ...
  1496. @property
  1497. def _var_type(self) -> types.GenericType: ...
  1498. @property
  1499. def _var_data(self) -> VarData: ...
  1500. class CachedVarOperation:
  1501. """Base class for cached var operations to lower boilerplate code."""
  1502. def __post_init__(self):
  1503. """Post-initialize the CachedVarOperation."""
  1504. object.__delattr__(self, "_js_expr")
  1505. def __getattr__(self, name: str) -> Any:
  1506. """Get an attribute of the var.
  1507. Args:
  1508. name: The name of the attribute.
  1509. Returns:
  1510. The attribute.
  1511. """
  1512. if name == "_js_expr":
  1513. return self._cached_var_name
  1514. parent_classes = inspect.getmro(type(self))
  1515. next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1]
  1516. return next_class.__getattr__(self, name)
  1517. def _get_all_var_data(self) -> VarData | None:
  1518. """Get all VarData associated with the Var.
  1519. Returns:
  1520. The VarData of the components and all of its children.
  1521. """
  1522. return self._cached_get_all_var_data
  1523. @cached_property_no_lock
  1524. def _cached_get_all_var_data(self: VarProtocol) -> VarData | None:
  1525. """Get the cached VarData.
  1526. Returns:
  1527. The cached VarData.
  1528. """
  1529. return VarData.merge(
  1530. *(
  1531. value._get_all_var_data() if isinstance(value, Var) else None
  1532. for value in (
  1533. getattr(self, field.name) for field in dataclasses.fields(self)
  1534. )
  1535. ),
  1536. self._var_data,
  1537. )
  1538. def __hash__(self: DataclassInstance) -> int:
  1539. """Calculate the hash of the object.
  1540. Returns:
  1541. The hash of the object.
  1542. """
  1543. return hash(
  1544. (
  1545. type(self).__name__,
  1546. *[
  1547. getattr(self, field.name)
  1548. for field in dataclasses.fields(self)
  1549. if field.name not in ["_js_expr", "_var_data", "_var_type"]
  1550. ],
  1551. )
  1552. )
  1553. def and_operation(
  1554. a: Var[VAR_TYPE] | Any, b: Var[OTHER_VAR_TYPE] | Any
  1555. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  1556. """Perform a logical AND operation on two variables.
  1557. Args:
  1558. a: The first variable.
  1559. b: The second variable.
  1560. Returns:
  1561. The result of the logical AND operation.
  1562. """
  1563. return _and_operation(a, b)
  1564. @var_operation
  1565. def _and_operation(a: Var, b: Var):
  1566. """Perform a logical AND operation on two variables.
  1567. Args:
  1568. a: The first variable.
  1569. b: The second variable.
  1570. Returns:
  1571. The result of the logical AND operation.
  1572. """
  1573. return var_operation_return(
  1574. js_expression=f"({a} && {b})",
  1575. var_type=unionize(a._var_type, b._var_type),
  1576. )
  1577. def or_operation(
  1578. a: Var[VAR_TYPE] | Any, b: Var[OTHER_VAR_TYPE] | Any
  1579. ) -> Var[VAR_TYPE | OTHER_VAR_TYPE]:
  1580. """Perform a logical OR operation on two variables.
  1581. Args:
  1582. a: The first variable.
  1583. b: The second variable.
  1584. Returns:
  1585. The result of the logical OR operation.
  1586. """
  1587. return _or_operation(a, b)
  1588. @var_operation
  1589. def _or_operation(a: Var, b: Var):
  1590. """Perform a logical OR operation on two variables.
  1591. Args:
  1592. a: The first variable.
  1593. b: The second variable.
  1594. Returns:
  1595. The result of the logical OR operation.
  1596. """
  1597. return var_operation_return(
  1598. js_expression=f"({a} || {b})",
  1599. var_type=unionize(a._var_type, b._var_type),
  1600. )
  1601. RETURN_TYPE = TypeVar("RETURN_TYPE")
  1602. DICT_KEY = TypeVar("DICT_KEY")
  1603. DICT_VAL = TypeVar("DICT_VAL")
  1604. LIST_INSIDE = TypeVar("LIST_INSIDE")
  1605. class FakeComputedVarBaseClass(property):
  1606. """A fake base class for ComputedVar to avoid inheriting from property."""
  1607. __pydantic_run_validation__ = False
  1608. def is_computed_var(obj: Any) -> TypeGuard[ComputedVar]:
  1609. """Check if the object is a ComputedVar.
  1610. Args:
  1611. obj: The object to check.
  1612. Returns:
  1613. Whether the object is a ComputedVar.
  1614. """
  1615. return isinstance(obj, FakeComputedVarBaseClass)
  1616. @dataclasses.dataclass(
  1617. eq=False,
  1618. frozen=True,
  1619. slots=True,
  1620. )
  1621. class ComputedVar(Var[RETURN_TYPE]):
  1622. """A field with computed getters."""
  1623. # Whether to track dependencies and cache computed values
  1624. _cache: bool = dataclasses.field(default=False)
  1625. # Whether the computed var is a backend var
  1626. _backend: bool = dataclasses.field(default=False)
  1627. # The initial value of the computed var
  1628. _initial_value: RETURN_TYPE | types.Unset = dataclasses.field(default=types.Unset())
  1629. # Explicit var dependencies to track
  1630. _static_deps: dict[str | None, set[str]] = dataclasses.field(default_factory=dict)
  1631. # Whether var dependencies should be auto-determined
  1632. _auto_deps: bool = dataclasses.field(default=True)
  1633. # Interval at which the computed var should be updated
  1634. _update_interval: datetime.timedelta | None = dataclasses.field(default=None)
  1635. _fget: Callable[[BaseState], RETURN_TYPE] = dataclasses.field(
  1636. default_factory=lambda: lambda _: None
  1637. ) # pyright: ignore [reportAssignmentType]
  1638. def __init__(
  1639. self,
  1640. fget: Callable[[BASE_STATE], RETURN_TYPE],
  1641. initial_value: RETURN_TYPE | types.Unset = types.Unset(),
  1642. cache: bool = True,
  1643. deps: list[str | Var] | None = None,
  1644. auto_deps: bool = True,
  1645. interval: int | datetime.timedelta | None = None,
  1646. backend: bool | None = None,
  1647. **kwargs,
  1648. ):
  1649. """Initialize a ComputedVar.
  1650. Args:
  1651. fget: The getter function.
  1652. initial_value: The initial value of the computed var.
  1653. cache: Whether to cache the computed value.
  1654. deps: Explicit var dependencies to track.
  1655. auto_deps: Whether var dependencies should be auto-determined.
  1656. interval: Interval at which the computed var should be updated.
  1657. backend: Whether the computed var is a backend var.
  1658. **kwargs: additional attributes to set on the instance
  1659. Raises:
  1660. TypeError: If the computed var dependencies are not Var instances or var names.
  1661. UntypedComputedVarError: If the computed var is untyped.
  1662. """
  1663. hint = kwargs.pop("return_type", None) or get_type_hints(fget).get(
  1664. "return", Any
  1665. )
  1666. if hint is Any:
  1667. raise UntypedComputedVarError(var_name=fget.__name__)
  1668. kwargs.setdefault("_js_expr", fget.__name__)
  1669. kwargs.setdefault("_var_type", hint)
  1670. Var.__init__(
  1671. self,
  1672. _js_expr=kwargs.pop("_js_expr"),
  1673. _var_type=kwargs.pop("_var_type"),
  1674. _var_data=kwargs.pop("_var_data", None),
  1675. )
  1676. if kwargs:
  1677. raise TypeError(f"Unexpected keyword arguments: {tuple(kwargs)}")
  1678. if backend is None:
  1679. backend = fget.__name__.startswith("_")
  1680. object.__setattr__(self, "_backend", backend)
  1681. object.__setattr__(self, "_initial_value", initial_value)
  1682. object.__setattr__(self, "_cache", cache)
  1683. if isinstance(interval, int):
  1684. interval = datetime.timedelta(seconds=interval)
  1685. object.__setattr__(self, "_update_interval", interval)
  1686. object.__setattr__(
  1687. self,
  1688. "_static_deps",
  1689. self._calculate_static_deps(deps),
  1690. )
  1691. object.__setattr__(self, "_auto_deps", auto_deps)
  1692. object.__setattr__(self, "_fget", fget)
  1693. def _calculate_static_deps(
  1694. self,
  1695. deps: list[str | Var] | dict[str | None, set[str]] | None = None,
  1696. ) -> dict[str | None, set[str]]:
  1697. """Calculate the static dependencies of the computed var from user input or existing dependencies.
  1698. Args:
  1699. deps: The user input dependencies or existing dependencies.
  1700. Returns:
  1701. The static dependencies.
  1702. """
  1703. if isinstance(deps, dict):
  1704. # Assume a dict is coming from _replace, so no special processing.
  1705. return deps
  1706. _static_deps = {}
  1707. if deps is not None:
  1708. for dep in deps:
  1709. _static_deps = self._add_static_dep(dep, _static_deps)
  1710. return _static_deps
  1711. def _add_static_dep(
  1712. self, dep: str | Var, deps: dict[str | None, set[str]] | None = None
  1713. ) -> dict[str | None, set[str]]:
  1714. """Add a static dependency to the computed var or existing dependency set.
  1715. Args:
  1716. dep: The dependency to add.
  1717. deps: The existing dependency set.
  1718. Returns:
  1719. The updated dependency set.
  1720. Raises:
  1721. TypeError: If the computed var dependencies are not Var instances or var names.
  1722. """
  1723. if deps is None:
  1724. deps = self._static_deps
  1725. if isinstance(dep, Var):
  1726. state_name = (
  1727. all_var_data.state
  1728. if (all_var_data := dep._get_all_var_data()) and all_var_data.state
  1729. else None
  1730. )
  1731. if all_var_data is not None:
  1732. var_name = all_var_data.field_name
  1733. else:
  1734. var_name = dep._js_expr
  1735. deps.setdefault(state_name, set()).add(var_name)
  1736. elif isinstance(dep, str) and dep != "":
  1737. deps.setdefault(None, set()).add(dep)
  1738. else:
  1739. raise TypeError(
  1740. "ComputedVar dependencies must be Var instances or var names (non-empty strings)."
  1741. )
  1742. return deps
  1743. @override
  1744. def _replace(
  1745. self,
  1746. merge_var_data: VarData | None = None,
  1747. **kwargs: Any,
  1748. ) -> Self:
  1749. """Replace the attributes of the ComputedVar.
  1750. Args:
  1751. merge_var_data: VarData to merge into the existing VarData.
  1752. **kwargs: Var fields to update.
  1753. Returns:
  1754. The new ComputedVar instance.
  1755. Raises:
  1756. TypeError: If kwargs contains keys that are not allowed.
  1757. """
  1758. if "deps" in kwargs:
  1759. kwargs["deps"] = self._calculate_static_deps(kwargs["deps"])
  1760. field_values = {
  1761. "fget": kwargs.pop("fget", self._fget),
  1762. "initial_value": kwargs.pop("initial_value", self._initial_value),
  1763. "cache": kwargs.pop("cache", self._cache),
  1764. "deps": kwargs.pop("deps", copy.copy(self._static_deps)),
  1765. "auto_deps": kwargs.pop("auto_deps", self._auto_deps),
  1766. "interval": kwargs.pop("interval", self._update_interval),
  1767. "backend": kwargs.pop("backend", self._backend),
  1768. "_js_expr": kwargs.pop("_js_expr", self._js_expr),
  1769. "_var_type": kwargs.pop("_var_type", self._var_type),
  1770. "_var_data": kwargs.pop(
  1771. "_var_data", VarData.merge(self._var_data, merge_var_data)
  1772. ),
  1773. "return_type": kwargs.pop("return_type", self._var_type),
  1774. }
  1775. if kwargs:
  1776. unexpected_kwargs = ", ".join(kwargs.keys())
  1777. raise TypeError(f"Unexpected keyword arguments: {unexpected_kwargs}")
  1778. return type(self)(**field_values)
  1779. @property
  1780. def _cache_attr(self) -> str:
  1781. """Get the attribute used to cache the value on the instance.
  1782. Returns:
  1783. An attribute name.
  1784. """
  1785. return f"__cached_{self._js_expr}"
  1786. @property
  1787. def _last_updated_attr(self) -> str:
  1788. """Get the attribute used to store the last updated timestamp.
  1789. Returns:
  1790. An attribute name.
  1791. """
  1792. return f"__last_updated_{self._js_expr}"
  1793. def needs_update(self, instance: BaseState) -> bool:
  1794. """Check if the computed var needs to be updated.
  1795. Args:
  1796. instance: The state instance that the computed var is attached to.
  1797. Returns:
  1798. True if the computed var needs to be updated, False otherwise.
  1799. """
  1800. if self._update_interval is None:
  1801. return False
  1802. last_updated = getattr(instance, self._last_updated_attr, None)
  1803. if last_updated is None:
  1804. return True
  1805. return datetime.datetime.now() - last_updated > self._update_interval
  1806. @overload
  1807. def __get__(
  1808. self: ComputedVar[bool],
  1809. instance: None,
  1810. owner: type,
  1811. ) -> BooleanVar: ...
  1812. @overload
  1813. def __get__(
  1814. self: ComputedVar[int] | ComputedVar[float],
  1815. instance: None,
  1816. owner: type,
  1817. ) -> NumberVar: ...
  1818. @overload
  1819. def __get__(
  1820. self: ComputedVar[str],
  1821. instance: None,
  1822. owner: type,
  1823. ) -> StringVar: ...
  1824. @overload
  1825. def __get__(
  1826. self: ComputedVar[MAPPING_TYPE],
  1827. instance: None,
  1828. owner: type,
  1829. ) -> ObjectVar[MAPPING_TYPE]: ...
  1830. @overload
  1831. def __get__(
  1832. self: ComputedVar[list[LIST_INSIDE]],
  1833. instance: None,
  1834. owner: type,
  1835. ) -> ArrayVar[list[LIST_INSIDE]]: ...
  1836. @overload
  1837. def __get__(
  1838. self: ComputedVar[tuple[LIST_INSIDE, ...]],
  1839. instance: None,
  1840. owner: type,
  1841. ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
  1842. @overload
  1843. def __get__(
  1844. self: ComputedVar[BASE_TYPE],
  1845. instance: None,
  1846. owner: type,
  1847. ) -> ObjectVar[BASE_TYPE]: ...
  1848. @overload
  1849. def __get__(
  1850. self: ComputedVar[SQLA_TYPE],
  1851. instance: None,
  1852. owner: type,
  1853. ) -> ObjectVar[SQLA_TYPE]: ...
  1854. if TYPE_CHECKING:
  1855. @overload
  1856. def __get__(
  1857. self: ComputedVar[DATACLASS_TYPE], instance: None, owner: Any
  1858. ) -> ObjectVar[DATACLASS_TYPE]: ...
  1859. @overload
  1860. def __get__(self, instance: None, owner: type) -> ComputedVar[RETURN_TYPE]: ...
  1861. @overload
  1862. def __get__(self, instance: BaseState, owner: type) -> RETURN_TYPE: ...
  1863. def __get__(self, instance: BaseState | None, owner: type):
  1864. """Get the ComputedVar value.
  1865. If the value is already cached on the instance, return the cached value.
  1866. Args:
  1867. instance: the instance of the class accessing this computed var.
  1868. owner: the class that this descriptor is attached to.
  1869. Returns:
  1870. The value of the var for the given instance.
  1871. """
  1872. if instance is None:
  1873. state_where_defined = owner
  1874. while self._js_expr in state_where_defined.inherited_vars:
  1875. state_where_defined = state_where_defined.get_parent_state()
  1876. field_name = (
  1877. format_state_name(state_where_defined.get_full_name())
  1878. + "."
  1879. + self._js_expr
  1880. )
  1881. return dispatch(
  1882. field_name,
  1883. var_data=VarData.from_state(state_where_defined, self._js_expr),
  1884. result_var_type=self._var_type,
  1885. existing_var=self,
  1886. )
  1887. if not self._cache:
  1888. value = self.fget(instance)
  1889. else:
  1890. # handle caching
  1891. if not hasattr(instance, self._cache_attr) or self.needs_update(instance):
  1892. # Set cache attr on state instance.
  1893. setattr(instance, self._cache_attr, self.fget(instance))
  1894. # Ensure the computed var gets serialized to redis.
  1895. instance._was_touched = True
  1896. # Set the last updated timestamp on the state instance.
  1897. setattr(instance, self._last_updated_attr, datetime.datetime.now())
  1898. value = getattr(instance, self._cache_attr)
  1899. self._check_deprecated_return_type(instance, value)
  1900. return value
  1901. def _check_deprecated_return_type(self, instance: BaseState, value: Any) -> None:
  1902. if not _isinstance(value, self._var_type, nested=1, treat_var_as_type=False):
  1903. console.error(
  1904. f"Computed var '{type(instance).__name__}.{self._js_expr}' must return"
  1905. f" a value of type '{escape(str(self._var_type))}', got '{value!s}' of type {type(value)}."
  1906. )
  1907. def _deps(
  1908. self,
  1909. objclass: type[BaseState],
  1910. obj: FunctionType | CodeType | None = None,
  1911. ) -> dict[str, set[str]]:
  1912. """Determine var dependencies of this ComputedVar.
  1913. Save references to attributes accessed on "self" or other fetched states.
  1914. Recursively called when the function makes a method call on "self" or
  1915. define comprehensions or nested functions that may reference "self".
  1916. Args:
  1917. objclass: the class obj this ComputedVar is attached to.
  1918. obj: the object to disassemble (defaults to the fget function).
  1919. Returns:
  1920. A dictionary mapping state names to the set of variable names
  1921. accessed by the given obj.
  1922. """
  1923. from .dep_tracking import DependencyTracker
  1924. d = {}
  1925. if self._static_deps:
  1926. d.update(self._static_deps)
  1927. # None is a placeholder for the current state class.
  1928. if None in d:
  1929. d[objclass.get_full_name()] = d.pop(None)
  1930. if not self._auto_deps:
  1931. return d
  1932. if obj is None:
  1933. fget = self._fget
  1934. if fget is not None:
  1935. obj = cast(FunctionType, fget)
  1936. else:
  1937. return d
  1938. try:
  1939. return DependencyTracker(
  1940. func=obj, state_cls=objclass, dependencies=d
  1941. ).dependencies
  1942. except Exception as e:
  1943. console.warn(
  1944. "Failed to automatically determine dependencies for computed var "
  1945. f"{objclass.__name__}.{self._js_expr}: {e}. "
  1946. "Provide static_deps and set auto_deps=False to suppress this warning."
  1947. )
  1948. return d
  1949. def mark_dirty(self, instance: BaseState) -> None:
  1950. """Mark this ComputedVar as dirty.
  1951. Args:
  1952. instance: the state instance that needs to recompute the value.
  1953. """
  1954. with contextlib.suppress(AttributeError):
  1955. delattr(instance, self._cache_attr)
  1956. def add_dependency(self, objclass: type[BaseState], dep: Var):
  1957. """Explicitly add a dependency to the ComputedVar.
  1958. After adding the dependency, when the `dep` changes, this computed var
  1959. will be marked dirty.
  1960. Args:
  1961. objclass: The class obj this ComputedVar is attached to.
  1962. dep: The dependency to add.
  1963. Raises:
  1964. VarDependencyError: If the dependency is not a Var instance with a
  1965. state and field name
  1966. """
  1967. if all_var_data := dep._get_all_var_data():
  1968. state_name = all_var_data.state
  1969. if state_name:
  1970. var_name = all_var_data.field_name
  1971. if var_name:
  1972. self._static_deps.setdefault(state_name, set()).add(var_name)
  1973. objclass.get_root_state().get_class_substate(
  1974. state_name
  1975. )._var_dependencies.setdefault(var_name, set()).add(
  1976. (objclass.get_full_name(), self._js_expr)
  1977. )
  1978. return
  1979. raise VarDependencyError(
  1980. "ComputedVar dependencies must be Var instances with a state and "
  1981. f"field name, got {dep!r}."
  1982. )
  1983. def _determine_var_type(self) -> type:
  1984. """Get the type of the var.
  1985. Returns:
  1986. The type of the var.
  1987. """
  1988. hints = get_type_hints(self._fget)
  1989. if "return" in hints:
  1990. return hints["return"]
  1991. return Any # pyright: ignore [reportReturnType]
  1992. @property
  1993. def __class__(self) -> type:
  1994. """Get the class of the var.
  1995. Returns:
  1996. The class of the var.
  1997. """
  1998. return FakeComputedVarBaseClass
  1999. @property
  2000. def fget(self) -> Callable[[BaseState], RETURN_TYPE]:
  2001. """Get the getter function.
  2002. Returns:
  2003. The getter function.
  2004. """
  2005. return self._fget
  2006. class DynamicRouteVar(ComputedVar[str | list[str]]):
  2007. """A ComputedVar that represents a dynamic route."""
  2008. pass
  2009. async def _default_async_computed_var(_self: BaseState) -> Any:
  2010. return None
  2011. @dataclasses.dataclass(
  2012. eq=False,
  2013. frozen=True,
  2014. init=False,
  2015. slots=True,
  2016. )
  2017. class AsyncComputedVar(ComputedVar[RETURN_TYPE]):
  2018. """A computed var that wraps a coroutinefunction."""
  2019. _fget: Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]] = (
  2020. dataclasses.field(default=_default_async_computed_var)
  2021. )
  2022. @overload
  2023. def __get__(
  2024. self: AsyncComputedVar[bool],
  2025. instance: None,
  2026. owner: type,
  2027. ) -> BooleanVar: ...
  2028. @overload
  2029. def __get__(
  2030. self: AsyncComputedVar[int] | ComputedVar[float],
  2031. instance: None,
  2032. owner: type,
  2033. ) -> NumberVar: ...
  2034. @overload
  2035. def __get__(
  2036. self: AsyncComputedVar[str],
  2037. instance: None,
  2038. owner: type,
  2039. ) -> StringVar: ...
  2040. @overload
  2041. def __get__(
  2042. self: AsyncComputedVar[MAPPING_TYPE],
  2043. instance: None,
  2044. owner: type,
  2045. ) -> ObjectVar[MAPPING_TYPE]: ...
  2046. @overload
  2047. def __get__(
  2048. self: AsyncComputedVar[list[LIST_INSIDE]],
  2049. instance: None,
  2050. owner: type,
  2051. ) -> ArrayVar[list[LIST_INSIDE]]: ...
  2052. @overload
  2053. def __get__(
  2054. self: AsyncComputedVar[tuple[LIST_INSIDE, ...]],
  2055. instance: None,
  2056. owner: type,
  2057. ) -> ArrayVar[tuple[LIST_INSIDE, ...]]: ...
  2058. @overload
  2059. def __get__(
  2060. self: AsyncComputedVar[BASE_TYPE],
  2061. instance: None,
  2062. owner: type,
  2063. ) -> ObjectVar[BASE_TYPE]: ...
  2064. @overload
  2065. def __get__(
  2066. self: AsyncComputedVar[SQLA_TYPE],
  2067. instance: None,
  2068. owner: type,
  2069. ) -> ObjectVar[SQLA_TYPE]: ...
  2070. if TYPE_CHECKING:
  2071. @overload
  2072. def __get__(
  2073. self: AsyncComputedVar[DATACLASS_TYPE], instance: None, owner: Any
  2074. ) -> ObjectVar[DATACLASS_TYPE]: ...
  2075. @overload
  2076. def __get__(self, instance: None, owner: type) -> AsyncComputedVar[RETURN_TYPE]: ...
  2077. @overload
  2078. def __get__(
  2079. self, instance: BaseState, owner: type
  2080. ) -> Coroutine[None, None, RETURN_TYPE]: ...
  2081. def __get__(
  2082. self, instance: BaseState | None, owner
  2083. ) -> Var | Coroutine[None, None, RETURN_TYPE]:
  2084. """Get the ComputedVar value.
  2085. If the value is already cached on the instance, return the cached value.
  2086. Args:
  2087. instance: the instance of the class accessing this computed var.
  2088. owner: the class that this descriptor is attached to.
  2089. Returns:
  2090. The value of the var for the given instance.
  2091. """
  2092. if instance is None:
  2093. return super(AsyncComputedVar, self).__get__(instance, owner)
  2094. if not self._cache:
  2095. async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE:
  2096. value = await self.fget(instance)
  2097. self._check_deprecated_return_type(instance, value)
  2098. return value
  2099. return _awaitable_result()
  2100. else:
  2101. # handle caching
  2102. async def _awaitable_result(instance: BaseState = instance) -> RETURN_TYPE:
  2103. if not hasattr(instance, self._cache_attr) or self.needs_update(
  2104. instance
  2105. ):
  2106. # Set cache attr on state instance.
  2107. setattr(instance, self._cache_attr, await self.fget(instance))
  2108. # Ensure the computed var gets serialized to redis.
  2109. instance._was_touched = True
  2110. # Set the last updated timestamp on the state instance.
  2111. setattr(instance, self._last_updated_attr, datetime.datetime.now())
  2112. value = getattr(instance, self._cache_attr)
  2113. self._check_deprecated_return_type(instance, value)
  2114. return value
  2115. return _awaitable_result()
  2116. @property
  2117. def fget(self) -> Callable[[BaseState], Coroutine[None, None, RETURN_TYPE]]:
  2118. """Get the getter function.
  2119. Returns:
  2120. The getter function.
  2121. """
  2122. return self._fget
  2123. if TYPE_CHECKING:
  2124. BASE_STATE = TypeVar("BASE_STATE", bound=BaseState)
  2125. @overload
  2126. def computed_var(
  2127. fget: None = None,
  2128. initial_value: Any | types.Unset = types.Unset(),
  2129. cache: bool = True,
  2130. deps: list[str | Var] | None = None,
  2131. auto_deps: bool = True,
  2132. interval: datetime.timedelta | int | None = None,
  2133. backend: bool | None = None,
  2134. **kwargs,
  2135. ) -> Callable[[Callable[[BASE_STATE], RETURN_TYPE]], ComputedVar[RETURN_TYPE]]: ... # pyright: ignore [reportInvalidTypeVarUse]
  2136. @overload
  2137. def computed_var(
  2138. fget: Callable[[BASE_STATE], RETURN_TYPE],
  2139. initial_value: RETURN_TYPE | types.Unset = types.Unset(),
  2140. cache: bool = True,
  2141. deps: list[str | Var] | None = None,
  2142. auto_deps: bool = True,
  2143. interval: datetime.timedelta | int | None = None,
  2144. backend: bool | None = None,
  2145. **kwargs,
  2146. ) -> ComputedVar[RETURN_TYPE]: ...
  2147. def computed_var(
  2148. fget: Callable[[BASE_STATE], Any] | None = None,
  2149. initial_value: Any | types.Unset = types.Unset(),
  2150. cache: bool = True,
  2151. deps: list[str | Var] | None = None,
  2152. auto_deps: bool = True,
  2153. interval: datetime.timedelta | int | None = None,
  2154. backend: bool | None = None,
  2155. **kwargs,
  2156. ) -> ComputedVar | Callable[[Callable[[BASE_STATE], Any]], ComputedVar]:
  2157. """A ComputedVar decorator with or without kwargs.
  2158. Args:
  2159. fget: The getter function.
  2160. initial_value: The initial value of the computed var.
  2161. cache: Whether to cache the computed value.
  2162. deps: Explicit var dependencies to track.
  2163. auto_deps: Whether var dependencies should be auto-determined.
  2164. interval: Interval at which the computed var should be updated.
  2165. backend: Whether the computed var is a backend var.
  2166. **kwargs: additional attributes to set on the instance
  2167. Returns:
  2168. A ComputedVar instance.
  2169. Raises:
  2170. ValueError: If caching is disabled and an update interval is set.
  2171. VarDependencyError: If user supplies dependencies without caching.
  2172. ComputedVarSignatureError: If the getter function has more than one argument.
  2173. """
  2174. if cache is False and interval is not None:
  2175. raise ValueError("Cannot set update interval without caching.")
  2176. if cache is False and (deps is not None or auto_deps is False):
  2177. raise VarDependencyError("Cannot track dependencies without caching.")
  2178. if fget is not None:
  2179. sign = inspect.signature(fget)
  2180. if len(sign.parameters) != 1:
  2181. raise ComputedVarSignatureError(fget.__name__, signature=str(sign))
  2182. if inspect.iscoroutinefunction(fget):
  2183. computed_var_cls = AsyncComputedVar
  2184. else:
  2185. computed_var_cls = ComputedVar
  2186. return computed_var_cls(
  2187. fget,
  2188. initial_value=initial_value,
  2189. cache=cache,
  2190. deps=deps,
  2191. auto_deps=auto_deps,
  2192. interval=interval,
  2193. backend=backend,
  2194. **kwargs,
  2195. )
  2196. def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar:
  2197. if inspect.iscoroutinefunction(fget):
  2198. computed_var_cls = AsyncComputedVar
  2199. else:
  2200. computed_var_cls = ComputedVar
  2201. return computed_var_cls(
  2202. fget,
  2203. initial_value=initial_value,
  2204. cache=cache,
  2205. deps=deps,
  2206. auto_deps=auto_deps,
  2207. interval=interval,
  2208. backend=backend,
  2209. **kwargs,
  2210. )
  2211. return wrapper
  2212. RETURN = TypeVar("RETURN")
  2213. class CustomVarOperationReturn(Var[RETURN]):
  2214. """Base class for custom var operations."""
  2215. @classmethod
  2216. def create(
  2217. cls,
  2218. js_expression: str,
  2219. _var_type: type[RETURN] | None = None,
  2220. _var_data: VarData | None = None,
  2221. ) -> CustomVarOperationReturn[RETURN]:
  2222. """Create a CustomVarOperation.
  2223. Args:
  2224. js_expression: The JavaScript expression to evaluate.
  2225. _var_type: The type of the var.
  2226. _var_data: Additional hooks and imports associated with the Var.
  2227. Returns:
  2228. The CustomVarOperation.
  2229. """
  2230. return CustomVarOperationReturn(
  2231. _js_expr=js_expression,
  2232. _var_type=_var_type or Any,
  2233. _var_data=_var_data,
  2234. )
  2235. def var_operation_return(
  2236. js_expression: str,
  2237. var_type: type[RETURN] | GenericType | None = None,
  2238. var_data: VarData | None = None,
  2239. ) -> CustomVarOperationReturn[RETURN]:
  2240. """Shortcut for creating a CustomVarOperationReturn.
  2241. Args:
  2242. js_expression: The JavaScript expression to evaluate.
  2243. var_type: The type of the var.
  2244. var_data: Additional hooks and imports associated with the Var.
  2245. Returns:
  2246. The CustomVarOperationReturn.
  2247. """
  2248. return CustomVarOperationReturn.create(
  2249. js_expression,
  2250. var_type,
  2251. var_data,
  2252. )
  2253. @dataclasses.dataclass(
  2254. eq=False,
  2255. frozen=True,
  2256. slots=True,
  2257. )
  2258. class CustomVarOperation(CachedVarOperation, Var[T]):
  2259. """Base class for custom var operations."""
  2260. _name: str = dataclasses.field(default="")
  2261. _args: tuple[tuple[str, Var], ...] = dataclasses.field(default_factory=tuple)
  2262. _return: CustomVarOperationReturn[T] = dataclasses.field(
  2263. default_factory=lambda: CustomVarOperationReturn.create("")
  2264. )
  2265. @cached_property_no_lock
  2266. def _cached_var_name(self) -> str:
  2267. """Get the cached var name.
  2268. Returns:
  2269. The cached var name.
  2270. """
  2271. return str(self._return)
  2272. @cached_property_no_lock
  2273. def _cached_get_all_var_data(self) -> VarData | None:
  2274. """Get the cached VarData.
  2275. Returns:
  2276. The cached VarData.
  2277. """
  2278. return VarData.merge(
  2279. *(arg[1]._get_all_var_data() for arg in self._args),
  2280. self._return._get_all_var_data(),
  2281. self._var_data,
  2282. )
  2283. @classmethod
  2284. def create(
  2285. cls,
  2286. name: str,
  2287. args: tuple[tuple[str, Var], ...],
  2288. return_var: CustomVarOperationReturn[T],
  2289. _var_data: VarData | None = None,
  2290. ) -> CustomVarOperation[T]:
  2291. """Create a CustomVarOperation.
  2292. Args:
  2293. name: The name of the operation.
  2294. args: The arguments to the operation.
  2295. return_var: The return var.
  2296. _var_data: Additional hooks and imports associated with the Var.
  2297. Returns:
  2298. The CustomVarOperation.
  2299. """
  2300. return CustomVarOperation(
  2301. _js_expr="",
  2302. _var_type=return_var._var_type,
  2303. _var_data=_var_data,
  2304. _name=name,
  2305. _args=args,
  2306. _return=return_var,
  2307. )
  2308. class NoneVar(Var[None], python_types=type(None)):
  2309. """A var representing None."""
  2310. @dataclasses.dataclass(
  2311. eq=False,
  2312. frozen=True,
  2313. slots=True,
  2314. )
  2315. class LiteralNoneVar(LiteralVar, NoneVar):
  2316. """A var representing None."""
  2317. _var_value: None = None
  2318. def json(self) -> str:
  2319. """Serialize the var to a JSON string.
  2320. Returns:
  2321. The JSON string.
  2322. """
  2323. return "null"
  2324. @classmethod
  2325. def create(
  2326. cls,
  2327. value: None = None,
  2328. _var_data: VarData | None = None,
  2329. ) -> LiteralNoneVar:
  2330. """Create a var from a value.
  2331. Args:
  2332. value: The value of the var. Must be None. Existed for compatibility with LiteralVar.
  2333. _var_data: Additional hooks and imports associated with the Var.
  2334. Returns:
  2335. The var.
  2336. """
  2337. return LiteralNoneVar(
  2338. _js_expr="null",
  2339. _var_type=None,
  2340. _var_data=_var_data,
  2341. )
  2342. def get_to_operation(var_subclass: type[Var]) -> type[ToOperation]:
  2343. """Get the ToOperation class for a given Var subclass.
  2344. Args:
  2345. var_subclass: The Var subclass.
  2346. Returns:
  2347. The ToOperation class.
  2348. Raises:
  2349. ValueError: If the ToOperation class cannot be found.
  2350. """
  2351. possible_classes = [
  2352. saved_var_subclass.to_var_subclass
  2353. for saved_var_subclass in _var_subclasses
  2354. if saved_var_subclass.var_subclass is var_subclass
  2355. ]
  2356. if not possible_classes:
  2357. raise ValueError(f"Could not find ToOperation for {var_subclass}.")
  2358. return possible_classes[0]
  2359. @dataclasses.dataclass(
  2360. eq=False,
  2361. frozen=True,
  2362. slots=True,
  2363. )
  2364. class StateOperation(CachedVarOperation, Var):
  2365. """A var operation that accesses a field on an object."""
  2366. _state_name: str = dataclasses.field(default="")
  2367. _field: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  2368. @cached_property_no_lock
  2369. def _cached_var_name(self) -> str:
  2370. """Get the cached var name.
  2371. Returns:
  2372. The cached var name.
  2373. """
  2374. return f"{self._state_name!s}.{self._field!s}"
  2375. def __getattr__(self, name: str) -> Any:
  2376. """Get an attribute of the var.
  2377. Args:
  2378. name: The name of the attribute.
  2379. Returns:
  2380. The attribute.
  2381. """
  2382. if name == "_js_expr":
  2383. return self._cached_var_name
  2384. return getattr(self._field, name)
  2385. @classmethod
  2386. def create(
  2387. cls,
  2388. state_name: str,
  2389. field: Var,
  2390. _var_data: VarData | None = None,
  2391. ) -> StateOperation:
  2392. """Create a DotOperation.
  2393. Args:
  2394. state_name: The name of the state.
  2395. field: The field of the state.
  2396. _var_data: Additional hooks and imports associated with the Var.
  2397. Returns:
  2398. The DotOperation.
  2399. """
  2400. return StateOperation(
  2401. _js_expr="",
  2402. _var_type=field._var_type,
  2403. _var_data=_var_data,
  2404. _state_name=state_name,
  2405. _field=field,
  2406. )
  2407. def get_uuid_string_var() -> Var:
  2408. """Return a Var that generates a single memoized UUID via .web/utils/state.js.
  2409. useMemo with an empty dependency array ensures that the generated UUID is
  2410. consistent across re-renders of the component.
  2411. Returns:
  2412. A Var that generates a UUID at runtime.
  2413. """
  2414. from reflex.utils.imports import ImportVar
  2415. from reflex.vars import Var
  2416. unique_uuid_var = get_unique_variable_name()
  2417. unique_uuid_var_data = VarData(
  2418. imports={
  2419. f"$/{constants.Dirs.STATE_PATH}": ImportVar(tag="generateUUID"),
  2420. "react": "useMemo",
  2421. },
  2422. hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
  2423. )
  2424. return Var(
  2425. _js_expr=unique_uuid_var,
  2426. _var_type=str,
  2427. _var_data=unique_uuid_var_data,
  2428. )
  2429. # Set of unique variable names.
  2430. USED_VARIABLES = set()
  2431. def get_unique_variable_name() -> str:
  2432. """Get a unique variable name.
  2433. Returns:
  2434. The unique variable name.
  2435. """
  2436. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  2437. if name not in USED_VARIABLES:
  2438. USED_VARIABLES.add(name)
  2439. return name
  2440. return get_unique_variable_name()
  2441. # Compile regex for finding reflex var tags.
  2442. _decode_var_pattern_re = (
  2443. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  2444. )
  2445. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  2446. # Defined global immutable vars.
  2447. _global_vars: dict[int, Var] = {}
  2448. dispatchers: dict[GenericType, Callable[[Var], Var]] = {}
  2449. def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]:
  2450. """Register a function to transform a Var.
  2451. Args:
  2452. fn: The function to register.
  2453. Returns:
  2454. The decorator.
  2455. Raises:
  2456. TypeError: If the return type of the function is not a Var.
  2457. TypeError: If the Var return type does not have a generic type.
  2458. ValueError: If a function for the generic type is already registered.
  2459. """
  2460. return_type = fn.__annotations__["return"]
  2461. origin = get_origin(return_type)
  2462. if origin is not Var:
  2463. raise TypeError(
  2464. f"Expected return type of {fn.__name__} to be a Var, got {origin}."
  2465. )
  2466. generic_args = get_args(return_type)
  2467. if not generic_args:
  2468. raise TypeError(
  2469. f"Expected Var return type of {fn.__name__} to have a generic type."
  2470. )
  2471. generic_type = get_origin(generic_args[0]) or generic_args[0]
  2472. if generic_type in dispatchers:
  2473. raise ValueError(f"Function for {generic_type} already registered.")
  2474. dispatchers[generic_type] = fn
  2475. return fn
  2476. def generic_type_to_actual_type_map(
  2477. generic_type: GenericType, actual_type: GenericType
  2478. ) -> dict[TypeVar, GenericType]:
  2479. """Map the generic type to the actual type.
  2480. Args:
  2481. generic_type: The generic type.
  2482. actual_type: The actual type.
  2483. Returns:
  2484. The mapping of type variables to actual types.
  2485. Raises:
  2486. TypeError: If the generic type and actual type do not match.
  2487. TypeError: If the number of generic arguments and actual arguments do not match.
  2488. """
  2489. generic_origin = get_origin(generic_type) or generic_type
  2490. actual_origin = get_origin(actual_type) or actual_type
  2491. if generic_origin is not actual_origin:
  2492. if isinstance(generic_origin, TypeVar):
  2493. return {generic_origin: actual_origin}
  2494. raise TypeError(
  2495. f"Type mismatch: expected {generic_origin}, got {actual_origin}."
  2496. )
  2497. generic_args = get_args(generic_type)
  2498. actual_args = get_args(actual_type)
  2499. if len(generic_args) != len(actual_args):
  2500. raise TypeError(
  2501. f"Number of generic arguments mismatch: expected {len(generic_args)}, got {len(actual_args)}."
  2502. )
  2503. # call recursively for nested generic types and merge the results
  2504. return {
  2505. k: v
  2506. for generic_arg, actual_arg in zip(generic_args, actual_args, strict=True)
  2507. for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items()
  2508. }
  2509. def resolve_generic_type_with_mapping(
  2510. generic_type: GenericType, type_mapping: dict[TypeVar, GenericType]
  2511. ):
  2512. """Resolve a generic type with a type mapping.
  2513. Args:
  2514. generic_type: The generic type.
  2515. type_mapping: The type mapping.
  2516. Returns:
  2517. The resolved generic type.
  2518. """
  2519. if isinstance(generic_type, TypeVar):
  2520. return type_mapping.get(generic_type, generic_type)
  2521. generic_origin = get_origin(generic_type) or generic_type
  2522. generic_args = get_args(generic_type)
  2523. if not generic_args:
  2524. return generic_type
  2525. mapping_for_older_python = {
  2526. list: List, # noqa: UP006
  2527. set: Set, # noqa: UP006
  2528. dict: Dict, # noqa: UP006
  2529. tuple: Tuple, # noqa: UP006
  2530. frozenset: FrozenSet, # noqa: UP006
  2531. }
  2532. return mapping_for_older_python.get(generic_origin, generic_origin)[
  2533. tuple(
  2534. resolve_generic_type_with_mapping(arg, type_mapping) for arg in generic_args
  2535. )
  2536. ]
  2537. def resolve_arg_type_from_return_type(
  2538. arg_type: GenericType, return_type: GenericType, actual_return_type: GenericType
  2539. ) -> GenericType:
  2540. """Resolve the argument type from the return type.
  2541. Args:
  2542. arg_type: The argument type.
  2543. return_type: The return type.
  2544. actual_return_type: The requested return type.
  2545. Returns:
  2546. The argument type without the generics that are resolved.
  2547. """
  2548. return resolve_generic_type_with_mapping(
  2549. arg_type, generic_type_to_actual_type_map(return_type, actual_return_type)
  2550. )
  2551. def dispatch(
  2552. field_name: str,
  2553. var_data: VarData,
  2554. result_var_type: GenericType,
  2555. existing_var: Var | None = None,
  2556. ) -> Var:
  2557. """Dispatch a Var to the appropriate transformation function.
  2558. Args:
  2559. field_name: The name of the field.
  2560. var_data: The VarData associated with the Var.
  2561. result_var_type: The type of the Var.
  2562. existing_var: The existing Var to transform. Optional.
  2563. Returns:
  2564. The transformed Var.
  2565. Raises:
  2566. TypeError: If the return type of the function is not a Var.
  2567. TypeError: If the Var return type does not have a generic type.
  2568. TypeError: If the first argument of the function is not a Var.
  2569. TypeError: If the first argument of the function does not have a generic type
  2570. """
  2571. result_origin_var_type = get_origin(result_var_type) or result_var_type
  2572. if result_origin_var_type in dispatchers:
  2573. fn = dispatchers[result_origin_var_type]
  2574. fn_first_arg_type = next(
  2575. iter(inspect.signature(fn).parameters.values())
  2576. ).annotation
  2577. fn_return = inspect.signature(fn).return_annotation
  2578. fn_return_origin = get_origin(fn_return) or fn_return
  2579. if fn_return_origin is not Var:
  2580. raise TypeError(
  2581. f"Expected return type of {fn.__name__} to be a Var, got {fn_return}."
  2582. )
  2583. fn_return_generic_args = get_args(fn_return)
  2584. if not fn_return_generic_args:
  2585. raise TypeError(f"Expected generic type of {fn_return} to be a type.")
  2586. arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type
  2587. if arg_origin is not Var:
  2588. raise TypeError(
  2589. f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}."
  2590. )
  2591. arg_generic_args = get_args(fn_first_arg_type)
  2592. if not arg_generic_args:
  2593. raise TypeError(
  2594. f"Expected generic type of {fn_first_arg_type} to be a type."
  2595. )
  2596. arg_type = arg_generic_args[0]
  2597. fn_return_type = fn_return_generic_args[0]
  2598. var = (
  2599. Var(
  2600. field_name,
  2601. _var_data=var_data,
  2602. _var_type=resolve_arg_type_from_return_type(
  2603. arg_type, fn_return_type, result_var_type
  2604. ),
  2605. ).guess_type()
  2606. if existing_var is None
  2607. else existing_var._replace(
  2608. _var_type=resolve_arg_type_from_return_type(
  2609. arg_type, fn_return_type, result_var_type
  2610. ),
  2611. _var_data=var_data,
  2612. _js_expr=field_name,
  2613. ).guess_type()
  2614. )
  2615. return fn(var)
  2616. if existing_var is not None:
  2617. return existing_var._replace(
  2618. _js_expr=field_name,
  2619. _var_data=var_data,
  2620. _var_type=result_var_type,
  2621. ).guess_type()
  2622. return Var(
  2623. field_name,
  2624. _var_data=var_data,
  2625. _var_type=result_var_type,
  2626. ).guess_type()
  2627. V = TypeVar("V")
  2628. BASE_TYPE = TypeVar("BASE_TYPE", bound=Base | None)
  2629. SQLA_TYPE = TypeVar("SQLA_TYPE", bound=DeclarativeBase | None)
  2630. if TYPE_CHECKING:
  2631. from _typeshed import DataclassInstance
  2632. DATACLASS_TYPE = TypeVar("DATACLASS_TYPE", bound=DataclassInstance | None)
  2633. FIELD_TYPE = TypeVar("FIELD_TYPE")
  2634. MAPPING_TYPE = TypeVar("MAPPING_TYPE", bound=Mapping | None)
  2635. class Field(Generic[FIELD_TYPE]):
  2636. """Shadow class for Var to allow for type hinting in the IDE."""
  2637. def __set__(self, instance: Any, value: FIELD_TYPE):
  2638. """Set the Var.
  2639. Args:
  2640. instance: The instance of the class setting the Var.
  2641. value: The value to set the Var to.
  2642. """
  2643. @overload
  2644. def __get__(self: Field[None], instance: None, owner: Any) -> NoneVar: ...
  2645. @overload
  2646. def __get__(
  2647. self: Field[bool] | Field[bool | None], instance: None, owner: Any
  2648. ) -> BooleanVar: ...
  2649. @overload
  2650. def __get__(
  2651. self: Field[int] | Field[int | None],
  2652. instance: None,
  2653. owner: Any,
  2654. ) -> NumberVar[int]: ...
  2655. @overload
  2656. def __get__(
  2657. self: Field[float]
  2658. | Field[int | float]
  2659. | Field[float | None]
  2660. | Field[int | float | None],
  2661. instance: None,
  2662. owner: Any,
  2663. ) -> NumberVar: ...
  2664. @overload
  2665. def __get__(
  2666. self: Field[str] | Field[str | None], instance: None, owner: Any
  2667. ) -> StringVar: ...
  2668. @overload
  2669. def __get__(
  2670. self: Field[list[V]]
  2671. | Field[set[V]]
  2672. | Field[list[V] | None]
  2673. | Field[set[V] | None],
  2674. instance: None,
  2675. owner: Any,
  2676. ) -> ArrayVar[Sequence[V]]: ...
  2677. @overload
  2678. def __get__(
  2679. self: Field[SEQUENCE_TYPE] | Field[SEQUENCE_TYPE | None],
  2680. instance: None,
  2681. owner: Any,
  2682. ) -> ArrayVar[SEQUENCE_TYPE]: ...
  2683. @overload
  2684. def __get__(
  2685. self: Field[MAPPING_TYPE] | Field[MAPPING_TYPE | None],
  2686. instance: None,
  2687. owner: Any,
  2688. ) -> ObjectVar[MAPPING_TYPE]: ...
  2689. @overload
  2690. def __get__(
  2691. self: Field[BASE_TYPE] | Field[BASE_TYPE | None], instance: None, owner: Any
  2692. ) -> ObjectVar[BASE_TYPE]: ...
  2693. @overload
  2694. def __get__(
  2695. self: Field[SQLA_TYPE] | Field[SQLA_TYPE | None], instance: None, owner: Any
  2696. ) -> ObjectVar[SQLA_TYPE]: ...
  2697. if TYPE_CHECKING:
  2698. @overload
  2699. def __get__(
  2700. self: Field[DATACLASS_TYPE] | Field[DATACLASS_TYPE | None],
  2701. instance: None,
  2702. owner: Any,
  2703. ) -> ObjectVar[DATACLASS_TYPE]: ...
  2704. @overload
  2705. def __get__(self, instance: None, owner: Any) -> Var[FIELD_TYPE]: ...
  2706. @overload
  2707. def __get__(self, instance: Any, owner: Any) -> FIELD_TYPE: ...
  2708. def __get__(self, instance: Any, owner: Any): # pyright: ignore [reportInconsistentOverload]
  2709. """Get the Var.
  2710. Args:
  2711. instance: The instance of the class accessing the Var.
  2712. owner: The class that the Var is attached to.
  2713. """
  2714. def field(value: FIELD_TYPE) -> Field[FIELD_TYPE]:
  2715. """Create a Field with a value.
  2716. Args:
  2717. value: The value of the Field.
  2718. Returns:
  2719. The Field.
  2720. """
  2721. return value # pyright: ignore [reportReturnType]