base.py 101 KB

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