base.py 87 KB

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