base.py 87 KB

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