base.py 97 KB

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