base.py 98 KB

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