base.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154
  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, EllipsisType, 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. Optional,
  28. Set,
  29. Tuple,
  30. Type,
  31. TypeVar,
  32. Union,
  33. cast,
  34. get_args,
  35. overload,
  36. )
  37. from typing_extensions import (
  38. ParamSpec,
  39. Protocol,
  40. TypeGuard,
  41. deprecated,
  42. get_type_hints,
  43. override,
  44. )
  45. from reflex import constants
  46. from reflex.base import Base
  47. from reflex.utils import console, imports, serializers, types
  48. from reflex.utils.exceptions import (
  49. VarAttributeError,
  50. VarDependencyError,
  51. VarTypeError,
  52. VarValueError,
  53. )
  54. from reflex.utils.format import format_state_name
  55. from reflex.utils.imports import (
  56. ImmutableParsedImportDict,
  57. ImportDict,
  58. ImportVar,
  59. ParsedImportDict,
  60. parse_imports,
  61. )
  62. from reflex.utils.types import (
  63. GenericType,
  64. Self,
  65. _isinstance,
  66. get_origin,
  67. has_args,
  68. unionize,
  69. )
  70. if TYPE_CHECKING:
  71. from reflex.state import BaseState
  72. from .function import ArgsFunctionOperation
  73. from .number import BooleanVar, NumberVar
  74. from .object import ObjectVar
  75. from .sequence import ArrayVar, StringVar
  76. VAR_TYPE = TypeVar("VAR_TYPE", covariant=True)
  77. OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE")
  78. warnings.filterwarnings("ignore", message="fields may not start with an underscore")
  79. P = ParamSpec("P")
  80. R = TypeVar("R")
  81. class ReflexCallable(Protocol[P, R]):
  82. """Protocol for a callable."""
  83. __call__: Callable[P, R]
  84. def unwrap_reflex_callalbe(
  85. callable_type: GenericType,
  86. ) -> Tuple[Union[EllipsisType, Tuple[GenericType, ...]], GenericType]:
  87. """Unwrap the ReflexCallable type.
  88. Args:
  89. callable_type: The ReflexCallable type to unwrap.
  90. Returns:
  91. The unwrapped ReflexCallable type.
  92. """
  93. if callable_type is ReflexCallable:
  94. return Ellipsis, Any
  95. if get_origin(callable_type) is not ReflexCallable:
  96. return Ellipsis, Any
  97. args = get_args(callable_type)
  98. if not args or len(args) != 2:
  99. return Ellipsis, Any
  100. return args
  101. @dataclasses.dataclass(
  102. eq=False,
  103. frozen=True,
  104. )
  105. class VarSubclassEntry:
  106. """Entry for a Var subclass."""
  107. var_subclass: Type[Var]
  108. to_var_subclass: Type[ToOperation]
  109. python_types: Tuple[GenericType, ...]
  110. _var_subclasses: List[VarSubclassEntry] = []
  111. _var_literal_subclasses: List[Tuple[Type[LiteralVar], VarSubclassEntry]] = []
  112. @dataclasses.dataclass(
  113. eq=True,
  114. frozen=True,
  115. )
  116. class VarData:
  117. """Metadata associated with a x."""
  118. # The name of the enclosing state.
  119. state: str = dataclasses.field(default="")
  120. # The name of the field in the state.
  121. field_name: str = dataclasses.field(default="")
  122. # Imports needed to render this var
  123. imports: ImmutableParsedImportDict = dataclasses.field(default_factory=tuple)
  124. # Hooks that need to be present in the component to render this var
  125. hooks: Tuple[str, ...] = dataclasses.field(default_factory=tuple)
  126. def __init__(
  127. self,
  128. state: str = "",
  129. field_name: str = "",
  130. imports: ImportDict | ParsedImportDict | None = None,
  131. hooks: dict[str, None] | None = None,
  132. ):
  133. """Initialize the var data.
  134. Args:
  135. state: The name of the enclosing state.
  136. field_name: The name of the field in the state.
  137. imports: Imports needed to render this var.
  138. hooks: Hooks that need to be present in the component to render this var.
  139. """
  140. immutable_imports: ImmutableParsedImportDict = tuple(
  141. sorted(
  142. ((k, tuple(sorted(v))) for k, v in parse_imports(imports or {}).items())
  143. )
  144. )
  145. object.__setattr__(self, "state", state)
  146. object.__setattr__(self, "field_name", field_name)
  147. object.__setattr__(self, "imports", immutable_imports)
  148. object.__setattr__(self, "hooks", tuple(hooks or {}))
  149. def old_school_imports(self) -> ImportDict:
  150. """Return the imports as a mutable dict.
  151. Returns:
  152. The imports as a mutable dict.
  153. """
  154. return dict((k, list(v)) for k, v in self.imports)
  155. def merge(*all: VarData | None) -> VarData | None:
  156. """Merge multiple var data objects.
  157. Args:
  158. *all: The var data objects to merge.
  159. Returns:
  160. The merged var data object.
  161. # noqa: DAR102 *all
  162. """
  163. all_var_datas = list(filter(None, all))
  164. if not all_var_datas:
  165. return None
  166. if len(all_var_datas) == 1:
  167. return all_var_datas[0]
  168. # Get the first non-empty field name or default to empty string.
  169. field_name = next(
  170. (var_data.field_name for var_data in all_var_datas if var_data.field_name),
  171. "",
  172. )
  173. # Get the first non-empty state or default to empty string.
  174. state = next(
  175. (var_data.state for var_data in all_var_datas if var_data.state), ""
  176. )
  177. hooks = {hook: None for var_data in all_var_datas for hook in var_data.hooks}
  178. _imports = imports.merge_imports(
  179. *(var_data.imports for var_data in all_var_datas)
  180. )
  181. if state or _imports or hooks or field_name:
  182. return VarData(
  183. state=state,
  184. field_name=field_name,
  185. imports=_imports,
  186. hooks=hooks,
  187. )
  188. return None
  189. def __bool__(self) -> bool:
  190. """Check if the var data is non-empty.
  191. Returns:
  192. True if any field is set to a non-default value.
  193. """
  194. return bool(self.state or self.imports or self.hooks or self.field_name)
  195. @classmethod
  196. def from_state(cls, state: Type[BaseState] | str, field_name: str = "") -> VarData:
  197. """Set the state of the var.
  198. Args:
  199. state: The state to set or the full name of the state.
  200. field_name: The name of the field in the state. Optional.
  201. Returns:
  202. The var with the set state.
  203. """
  204. from reflex.utils import format
  205. state_name = state if isinstance(state, str) else state.get_full_name()
  206. return VarData(
  207. state=state_name,
  208. field_name=field_name,
  209. hooks={
  210. "const {0} = useContext(StateContexts.{0})".format(
  211. format.format_state_name(state_name)
  212. ): None
  213. },
  214. imports={
  215. f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
  216. "react": [ImportVar(tag="useContext")],
  217. },
  218. )
  219. def _decode_var_immutable(value: str) -> tuple[VarData | None, str]:
  220. """Decode the state name from a formatted var.
  221. Args:
  222. value: The value to extract the state name from.
  223. Returns:
  224. The extracted state name and the value without the state name.
  225. """
  226. var_datas = []
  227. if isinstance(value, str):
  228. # fast path if there is no encoded VarData
  229. if constants.REFLEX_VAR_OPENING_TAG not in value:
  230. return None, value
  231. offset = 0
  232. # Find all tags.
  233. while m := _decode_var_pattern.search(value):
  234. start, end = m.span()
  235. value = value[:start] + value[end:]
  236. serialized_data = m.group(1)
  237. if serialized_data.isnumeric() or (
  238. serialized_data[0] == "-" and serialized_data[1:].isnumeric()
  239. ):
  240. # This is a global immutable var.
  241. var = _global_vars[int(serialized_data)]
  242. var_data = var._get_all_var_data()
  243. if var_data is not None:
  244. var_datas.append(var_data)
  245. offset += end - start
  246. return VarData.merge(*var_datas) if var_datas else None, value
  247. def can_use_in_object_var(cls: GenericType) -> bool:
  248. """Check if the class can be used in an ObjectVar.
  249. Args:
  250. cls: The class to check.
  251. Returns:
  252. Whether the class can be used in an ObjectVar.
  253. """
  254. if types.is_union(cls):
  255. return all(can_use_in_object_var(t) for t in types.get_args(cls))
  256. return (
  257. inspect.isclass(cls)
  258. and not issubclass(cls, Var)
  259. and serializers.can_serialize(cls, dict)
  260. )
  261. @dataclasses.dataclass(
  262. eq=False,
  263. frozen=True,
  264. )
  265. class Var(Generic[VAR_TYPE]):
  266. """Base class for immutable vars."""
  267. # The name of the var.
  268. _js_expr: str = dataclasses.field()
  269. # The type of the var.
  270. _var_type: types.GenericType = dataclasses.field(default=Any)
  271. # Extra metadata associated with the Var
  272. _var_data: Optional[VarData] = dataclasses.field(default=None)
  273. def __str__(self) -> str:
  274. """String representation of the var. Guaranteed to be a valid Javascript expression.
  275. Returns:
  276. The name of the var.
  277. """
  278. return self._js_expr
  279. @property
  280. def _var_is_local(self) -> bool:
  281. """Whether this is a local javascript variable.
  282. Returns:
  283. False
  284. """
  285. return False
  286. @property
  287. @deprecated("Use `_js_expr` instead.")
  288. def _var_name(self) -> str:
  289. """The name of the var.
  290. Returns:
  291. The name of the var.
  292. """
  293. return self._js_expr
  294. @property
  295. def _var_field_name(self) -> str:
  296. """The name of the field.
  297. Returns:
  298. The name of the field.
  299. """
  300. var_data = self._get_all_var_data()
  301. field_name = var_data.field_name if var_data else None
  302. return field_name or self._js_expr
  303. @property
  304. @deprecated("Use `_js_expr` instead.")
  305. def _var_name_unwrapped(self) -> str:
  306. """The name of the var without extra curly braces.
  307. Returns:
  308. The name of the var.
  309. """
  310. return self._js_expr
  311. @property
  312. def _var_is_string(self) -> bool:
  313. """Whether the var is a string literal.
  314. Returns:
  315. False
  316. """
  317. return False
  318. def __init_subclass__(
  319. cls,
  320. python_types: Tuple[GenericType, ...] | GenericType = types.Unset(),
  321. default_type: GenericType = types.Unset(),
  322. **kwargs,
  323. ):
  324. """Initialize the subclass.
  325. Args:
  326. python_types: The python types that the var represents.
  327. default_type: The default type of the var. Defaults to the first python type.
  328. **kwargs: Additional keyword arguments.
  329. """
  330. super().__init_subclass__(**kwargs)
  331. if python_types or default_type:
  332. python_types = (
  333. (python_types if isinstance(python_types, tuple) else (python_types,))
  334. if python_types
  335. else ()
  336. )
  337. default_type = default_type or (python_types[0] if python_types else Any)
  338. @dataclasses.dataclass(
  339. eq=False,
  340. frozen=True,
  341. **{"slots": True} if sys.version_info >= (3, 10) else {},
  342. )
  343. class ToVarOperation(ToOperation, cls):
  344. """Base class of converting a var to another var type."""
  345. _original: Var = dataclasses.field(
  346. default=Var(_js_expr="null", _var_type=None),
  347. )
  348. _default_var_type: ClassVar[GenericType] = default_type
  349. ToVarOperation.__name__ = f'To{cls.__name__.removesuffix("Var")}Operation'
  350. _var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types))
  351. def __post_init__(self):
  352. """Post-initialize the var."""
  353. # Decode any inline Var markup and apply it to the instance
  354. _var_data, _js_expr = _decode_var_immutable(self._js_expr)
  355. if _var_data or _js_expr != self._js_expr:
  356. self.__init__(
  357. **{
  358. **dataclasses.asdict(self),
  359. "_js_expr": _js_expr,
  360. "_var_data": VarData.merge(self._var_data, _var_data),
  361. }
  362. )
  363. def __hash__(self) -> int:
  364. """Define a hash function for the var.
  365. Returns:
  366. The hash of the var.
  367. """
  368. return hash((self._js_expr, self._var_type, self._var_data))
  369. def _get_all_var_data(self) -> VarData | None:
  370. """Get all VarData associated with the Var.
  371. Returns:
  372. The VarData of the components and all of its children.
  373. """
  374. return self._var_data
  375. def equals(self, other: Var) -> bool:
  376. """Check if two vars are equal.
  377. Args:
  378. other: The other var to compare.
  379. Returns:
  380. Whether the vars are equal.
  381. """
  382. return (
  383. self._js_expr == other._js_expr
  384. and self._var_type == other._var_type
  385. and self._get_all_var_data() == other._get_all_var_data()
  386. )
  387. @overload
  388. def _replace(
  389. self, _var_type: Type[OTHER_VAR_TYPE], merge_var_data=None, **kwargs: Any
  390. ) -> Var[OTHER_VAR_TYPE]: ...
  391. @overload
  392. def _replace(
  393. self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
  394. ) -> Self: ...
  395. def _replace(
  396. self, _var_type: GenericType | None = None, merge_var_data=None, **kwargs: Any
  397. ) -> Self | Var:
  398. """Make a copy of this Var with updated fields.
  399. Args:
  400. merge_var_data: VarData to merge into the existing VarData.
  401. **kwargs: Var fields to update.
  402. Returns:
  403. A new Var with the updated fields overwriting the corresponding fields in this Var.
  404. Raises:
  405. TypeError: If _var_is_local, _var_is_string, or _var_full_name_needs_state_prefix is not None.
  406. """
  407. if kwargs.get("_var_is_local", False) is not False:
  408. raise TypeError("The _var_is_local argument is not supported for Var.")
  409. if kwargs.get("_var_is_string", False) is not False:
  410. raise TypeError("The _var_is_string argument is not supported for Var.")
  411. if kwargs.get("_var_full_name_needs_state_prefix", False) is not False:
  412. raise TypeError(
  413. "The _var_full_name_needs_state_prefix argument is not supported for Var."
  414. )
  415. value_with_replaced = dataclasses.replace(
  416. self,
  417. _var_type=_var_type or self._var_type,
  418. _var_data=VarData.merge(
  419. kwargs.get("_var_data", self._var_data), merge_var_data
  420. ),
  421. **kwargs,
  422. )
  423. if (js_expr := kwargs.get("_js_expr")) is not None:
  424. object.__setattr__(value_with_replaced, "_js_expr", js_expr)
  425. return value_with_replaced
  426. @classmethod
  427. def create(
  428. cls,
  429. value: Any,
  430. _var_is_local: bool | None = None,
  431. _var_is_string: bool | None = None,
  432. _var_data: VarData | None = None,
  433. ) -> Var:
  434. """Create a var from a value.
  435. Args:
  436. value: The value to create the var from.
  437. _var_is_local: Whether the var is local. Deprecated.
  438. _var_is_string: Whether the var is a string literal. Deprecated.
  439. _var_data: Additional hooks and imports associated with the Var.
  440. Returns:
  441. The var.
  442. """
  443. if _var_is_local is not None:
  444. console.deprecate(
  445. feature_name="_var_is_local",
  446. reason="The _var_is_local argument is not supported for Var."
  447. "If you want to create a Var from a raw Javascript expression, use the constructor directly",
  448. deprecation_version="0.6.0",
  449. removal_version="0.7.0",
  450. )
  451. if _var_is_string is not None:
  452. console.deprecate(
  453. feature_name="_var_is_string",
  454. reason="The _var_is_string argument is not supported for Var."
  455. "If you want to create a Var from a raw Javascript expression, use the constructor directly",
  456. deprecation_version="0.6.0",
  457. removal_version="0.7.0",
  458. )
  459. # If the value is already a var, do nothing.
  460. if isinstance(value, Var):
  461. return value
  462. # Try to pull the imports and hooks from contained values.
  463. if not isinstance(value, str):
  464. return LiteralVar.create(value)
  465. if _var_is_string is False or _var_is_local is True:
  466. return cls(
  467. _js_expr=value,
  468. _var_data=_var_data,
  469. )
  470. return LiteralVar.create(value, _var_data=_var_data)
  471. @classmethod
  472. @deprecated("Use `.create()` instead.")
  473. def create_safe(
  474. cls,
  475. *args: Any,
  476. **kwargs: Any,
  477. ) -> Var:
  478. """Create a var from a value.
  479. Args:
  480. *args: The arguments to create the var from.
  481. **kwargs: The keyword arguments to create the var from.
  482. Returns:
  483. The var.
  484. """
  485. return cls.create(*args, **kwargs)
  486. def __format__(self, format_spec: str) -> str:
  487. """Format the var into a Javascript equivalent to an f-string.
  488. Args:
  489. format_spec: The format specifier (Ignored for now).
  490. Returns:
  491. The formatted var.
  492. """
  493. hashed_var = hash(self)
  494. _global_vars[hashed_var] = self
  495. # Encode the _var_data into the formatted output for tracking purposes.
  496. return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}"
  497. @overload
  498. def to(self, output: Type[str]) -> StringVar: ...
  499. @overload
  500. def to(self, output: Type[bool]) -> BooleanVar: ...
  501. @overload
  502. def to(self, output: type[int] | type[float]) -> NumberVar: ...
  503. @overload
  504. def to(
  505. self,
  506. output: type[list] | type[tuple] | type[set],
  507. ) -> ArrayVar: ...
  508. @overload
  509. def to(
  510. self,
  511. output: type[dict],
  512. ) -> ObjectVar[dict]: ...
  513. @overload
  514. def to(
  515. self, output: Type[ObjectVar], var_type: Type[VAR_INSIDE]
  516. ) -> ObjectVar[VAR_INSIDE]: ...
  517. @overload
  518. def to(
  519. self, output: Type[ObjectVar], var_type: None = None
  520. ) -> ObjectVar[VAR_TYPE]: ...
  521. @overload
  522. def to(self, output: VAR_SUBCLASS, var_type: None = None) -> VAR_SUBCLASS: ...
  523. @overload
  524. def to(
  525. self,
  526. output: Type[OUTPUT] | types.GenericType,
  527. var_type: types.GenericType | None = None,
  528. ) -> OUTPUT: ...
  529. def to(
  530. self,
  531. output: Type[OUTPUT] | types.GenericType,
  532. var_type: types.GenericType | None = None,
  533. ) -> Var:
  534. """Convert the var to a different type.
  535. Args:
  536. output: The output type.
  537. var_type: The type of the var.
  538. Returns:
  539. The converted var.
  540. """
  541. from .object import ObjectVar
  542. fixed_output_type = get_origin(output) or output
  543. # If the first argument is a python type, we map it to the corresponding Var type.
  544. for var_subclass in _var_subclasses[::-1]:
  545. if fixed_output_type in var_subclass.python_types:
  546. return self.to(var_subclass.var_subclass, output)
  547. if fixed_output_type is None:
  548. return get_to_operation(NoneVar).create(self) # type: ignore
  549. # Handle fixed_output_type being Base or a dataclass.
  550. if can_use_in_object_var(fixed_output_type):
  551. return self.to(ObjectVar, output)
  552. if inspect.isclass(output):
  553. for var_subclass in _var_subclasses[::-1]:
  554. if issubclass(output, var_subclass.var_subclass):
  555. current_var_type = self._var_type
  556. if current_var_type is Any:
  557. new_var_type = var_type
  558. else:
  559. new_var_type = var_type or current_var_type
  560. to_operation_return = var_subclass.to_var_subclass.create(
  561. value=self, _var_type=new_var_type
  562. )
  563. return to_operation_return # type: ignore
  564. # If we can't determine the first argument, we just replace the _var_type.
  565. if not issubclass(output, Var) or var_type is None:
  566. return dataclasses.replace(
  567. self,
  568. _var_type=output,
  569. )
  570. # We couldn't determine the output type to be any other Var type, so we replace the _var_type.
  571. if var_type is not None:
  572. return dataclasses.replace(
  573. self,
  574. _var_type=var_type,
  575. )
  576. return self
  577. @overload
  578. def guess_type(self: Var[str]) -> StringVar: ...
  579. @overload
  580. def guess_type(self: Var[bool]) -> BooleanVar: ...
  581. @overload
  582. def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ...
  583. @overload
  584. def guess_type(self: Var[list] | Var[tuple] | Var[set]) -> ArrayVar: ...
  585. @overload
  586. def guess_type(self: Var[dict]) -> ObjectVar[dict]: ...
  587. @overload
  588. def guess_type(self) -> Self: ...
  589. def guess_type(self) -> Var:
  590. """Guesses the type of the variable based on its `_var_type` attribute.
  591. Returns:
  592. Var: The guessed type of the variable.
  593. Raises:
  594. TypeError: If the type is not supported for guessing.
  595. """
  596. from .number import NumberVar
  597. from .object import ObjectVar
  598. var_type = self._var_type
  599. if var_type is None:
  600. return self.to(None)
  601. if types.is_optional(var_type):
  602. var_type = types.get_args(var_type)[0]
  603. if var_type is Any:
  604. return self
  605. fixed_type = get_origin(var_type) or var_type
  606. if fixed_type in types.UnionTypes:
  607. inner_types = get_args(var_type)
  608. if all(
  609. inspect.isclass(t) and issubclass(t, (int, float)) for t in inner_types
  610. ):
  611. return self.to(NumberVar, self._var_type)
  612. if can_use_in_object_var(var_type):
  613. return self.to(ObjectVar, self._var_type)
  614. return self
  615. if fixed_type is Literal:
  616. args = get_args(var_type)
  617. fixed_type = unionize(*(type(arg) for arg in args))
  618. if not inspect.isclass(fixed_type):
  619. raise TypeError(f"Unsupported type {var_type} for guess_type.")
  620. if fixed_type is None:
  621. return self.to(None)
  622. for var_subclass in _var_subclasses[::-1]:
  623. if issubclass(fixed_type, var_subclass.python_types):
  624. return self.to(var_subclass.var_subclass, self._var_type)
  625. if can_use_in_object_var(fixed_type):
  626. return self.to(ObjectVar, self._var_type)
  627. return self
  628. def _get_default_value(self) -> Any:
  629. """Get the default value of the var.
  630. Returns:
  631. The default value of the var.
  632. Raises:
  633. ImportError: If the var is a dataframe and pandas is not installed.
  634. """
  635. if types.is_optional(self._var_type):
  636. return None
  637. type_ = (
  638. get_origin(self._var_type)
  639. if types.is_generic_alias(self._var_type)
  640. else self._var_type
  641. )
  642. if type_ is Literal:
  643. args = get_args(self._var_type)
  644. return args[0] if args else None
  645. if issubclass(type_, str):
  646. return ""
  647. if issubclass(type_, types.get_args(Union[int, float])):
  648. return 0
  649. if issubclass(type_, bool):
  650. return False
  651. if issubclass(type_, list):
  652. return []
  653. if issubclass(type_, dict):
  654. return {}
  655. if issubclass(type_, tuple):
  656. return ()
  657. if types.is_dataframe(type_):
  658. try:
  659. import pandas as pd
  660. return pd.DataFrame()
  661. except ImportError as e:
  662. raise ImportError(
  663. "Please install pandas to use dataframes in your app."
  664. ) from e
  665. return set() if issubclass(type_, set) else None
  666. def _get_setter_name(self, include_state: bool = True) -> str:
  667. """Get the name of the var's generated setter function.
  668. Args:
  669. include_state: Whether to include the state name in the setter name.
  670. Returns:
  671. The name of the setter function.
  672. """
  673. setter = constants.SETTER_PREFIX + self._var_field_name
  674. var_data = self._get_all_var_data()
  675. if var_data is None:
  676. return setter
  677. if not include_state or var_data.state == "":
  678. return setter
  679. return ".".join((var_data.state, setter))
  680. def _get_setter(self) -> Callable[[BaseState, Any], None]:
  681. """Get the var's setter function.
  682. Returns:
  683. A function that that creates a setter for the var.
  684. """
  685. actual_name = self._var_field_name
  686. def setter(state: BaseState, value: Any):
  687. """Get the setter for the var.
  688. Args:
  689. state: The state within which we add the setter function.
  690. value: The value to set.
  691. """
  692. if self._var_type in [int, float]:
  693. try:
  694. value = self._var_type(value)
  695. setattr(state, actual_name, value)
  696. except ValueError:
  697. console.debug(
  698. f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value} to '{self._var_type.__name__}'. Value not set.",
  699. )
  700. else:
  701. setattr(state, actual_name, value)
  702. setter.__qualname__ = self._get_setter_name()
  703. return setter
  704. def _var_set_state(self, state: type[BaseState] | str):
  705. """Set the state of the var.
  706. Args:
  707. state: The state to set.
  708. Returns:
  709. The var with the state set.
  710. """
  711. formatted_state_name = (
  712. state
  713. if isinstance(state, str)
  714. else format_state_name(state.get_full_name())
  715. )
  716. return StateOperation.create(
  717. formatted_state_name,
  718. self,
  719. _var_data=VarData.merge(
  720. VarData.from_state(state, self._js_expr), self._var_data
  721. ),
  722. ).guess_type()
  723. def __eq__(self, other: Var | Any) -> BooleanVar:
  724. """Check if the current variable is equal to the given variable.
  725. Args:
  726. other (Var | Any): The variable to compare with.
  727. Returns:
  728. BooleanVar: A BooleanVar object representing the result of the equality check.
  729. """
  730. from .number import equal_operation
  731. return equal_operation(self, other)
  732. def __ne__(self, other: Var | Any) -> BooleanVar:
  733. """Check if the current object is not equal to the given object.
  734. Parameters:
  735. other (Var | Any): The object to compare with.
  736. Returns:
  737. BooleanVar: A BooleanVar object representing the result of the comparison.
  738. """
  739. from .number import equal_operation
  740. return (~equal_operation(self, other)).guess_type()
  741. def bool(self) -> BooleanVar:
  742. """Convert the var to a boolean.
  743. Returns:
  744. The boolean var.
  745. """
  746. from .number import boolify
  747. return boolify(self).guess_type()
  748. def __and__(self, other: Var | Any) -> Var:
  749. """Perform a logical AND operation on the current instance and another variable.
  750. Args:
  751. other: The variable to perform the logical AND operation with.
  752. Returns:
  753. A `BooleanVar` object representing the result of the logical AND operation.
  754. """
  755. return and_operation(self, other)
  756. def __rand__(self, other: Var | Any) -> Var:
  757. """Perform a logical AND operation on the current instance and another variable.
  758. Args:
  759. other: The variable to perform the logical AND operation with.
  760. Returns:
  761. A `BooleanVar` object representing the result of the logical AND operation.
  762. """
  763. return and_operation(other, self)
  764. def __or__(self, other: Var | Any) -> Var:
  765. """Perform a logical OR operation on the current instance and another variable.
  766. Args:
  767. other: The variable to perform the logical OR operation with.
  768. Returns:
  769. A `BooleanVar` object representing the result of the logical OR operation.
  770. """
  771. return or_operation(self, other)
  772. def __ror__(self, other: Var | Any) -> Var:
  773. """Perform a logical OR operation on the current instance and another variable.
  774. Args:
  775. other: The variable to perform the logical OR operation with.
  776. Returns:
  777. A `BooleanVar` object representing the result of the logical OR operation.
  778. """
  779. return or_operation(other, self)
  780. def __invert__(self) -> BooleanVar:
  781. """Perform a logical NOT operation on the current instance.
  782. Returns:
  783. A `BooleanVar` object representing the result of the logical NOT operation.
  784. """
  785. return (~self.bool()).guess_type()
  786. def to_string(self, use_json: bool = True) -> StringVar:
  787. """Convert the var to a string.
  788. Args:
  789. use_json: Whether to use JSON stringify. If False, uses Object.prototype.toString.
  790. Returns:
  791. The string var.
  792. """
  793. from .function import JSON_STRINGIFY, PROTOTYPE_TO_STRING
  794. from .sequence import StringVar
  795. return (
  796. JSON_STRINGIFY.call(self).to(StringVar)
  797. if use_json
  798. else PROTOTYPE_TO_STRING.call(self).to(StringVar)
  799. )
  800. def _as_ref(self) -> Var:
  801. """Get a reference to the var.
  802. Returns:
  803. The reference to the var.
  804. """
  805. from .object import ObjectVar
  806. refs = Var(
  807. _js_expr="refs",
  808. _var_data=VarData(
  809. imports={
  810. f"$/{constants.Dirs.STATE_PATH}": [imports.ImportVar(tag="refs")]
  811. }
  812. ),
  813. ).to(ObjectVar, Dict[str, str])
  814. return refs[LiteralVar.create(str(self))]
  815. @deprecated("Use `.js_type()` instead.")
  816. def _type(self) -> StringVar:
  817. """Returns the type of the object.
  818. This method uses the `typeof` function from the `FunctionStringVar` class
  819. to determine the type of the object.
  820. Returns:
  821. StringVar: A string variable representing the type of the object.
  822. """
  823. return self.js_type()
  824. def js_type(self) -> StringVar:
  825. """Returns the javascript type of the object.
  826. This method uses the `typeof` function from the `FunctionStringVar` class
  827. to determine the type of the object.
  828. Returns:
  829. StringVar: A string variable representing the type of the object.
  830. """
  831. from .function import FunctionStringVar
  832. from .sequence import StringVar
  833. type_of = FunctionStringVar("typeof")
  834. return type_of.call(self).to(StringVar)
  835. def _without_data(self):
  836. """Create a copy of the var without the data.
  837. Returns:
  838. The var without the data.
  839. """
  840. return dataclasses.replace(self, _var_data=None)
  841. def __get__(self, instance: Any, owner: Any):
  842. """Get the var.
  843. Args:
  844. instance: The instance to get the var from.
  845. owner: The owner of the var.
  846. Returns:
  847. The var.
  848. """
  849. return self
  850. def __getattr__(self, name: str):
  851. """Get an attribute of the var.
  852. Args:
  853. name: The name of the attribute.
  854. Returns:
  855. The attribute.
  856. Raises:
  857. VarAttributeError: If the attribute does not exist.
  858. TypeError: If the var type is Any.
  859. """
  860. if name.startswith("_"):
  861. return self.__getattribute__(name)
  862. if name == "contains":
  863. raise TypeError(
  864. f"Var of type {self._var_type} does not support contains check."
  865. )
  866. if name == "reverse":
  867. raise TypeError("Cannot reverse non-list var.")
  868. if self._var_type is Any:
  869. raise TypeError(
  870. f"You must provide an annotation for the state var `{str(self)}`. Annotation cannot be `{self._var_type}`."
  871. )
  872. if name in REPLACED_NAMES:
  873. raise VarAttributeError(
  874. f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
  875. )
  876. raise VarAttributeError(
  877. f"The State var has no attribute '{name}' or may have been annotated wrongly.",
  878. )
  879. def _decode(self) -> Any:
  880. """Decode Var as a python value.
  881. Note that Var with state set cannot be decoded python-side and will be
  882. returned as full_name.
  883. Returns:
  884. The decoded value or the Var name.
  885. """
  886. if isinstance(self, LiteralVar):
  887. return self._var_value # type: ignore
  888. try:
  889. return json.loads(str(self))
  890. except ValueError:
  891. return str(self)
  892. @property
  893. def _var_state(self) -> str:
  894. """Compat method for getting the state.
  895. Returns:
  896. The state name associated with the var.
  897. """
  898. var_data = self._get_all_var_data()
  899. return var_data.state if var_data else ""
  900. @overload
  901. @classmethod
  902. def range(cls, stop: int | NumberVar, /) -> ArrayVar[List[int]]: ...
  903. @overload
  904. @classmethod
  905. def range(
  906. cls,
  907. start: int | NumberVar,
  908. end: int | NumberVar,
  909. step: int | NumberVar = 1,
  910. /,
  911. ) -> ArrayVar[List[int]]: ...
  912. @classmethod
  913. def range(
  914. cls,
  915. first_endpoint: int | NumberVar,
  916. second_endpoint: int | NumberVar | None = None,
  917. step: int | NumberVar | None = None,
  918. ) -> ArrayVar[List[int]]:
  919. """Create a range of numbers.
  920. Args:
  921. first_endpoint: The end of the range if second_endpoint is not provided, otherwise the start of the range.
  922. second_endpoint: The end of the range.
  923. step: The step of the range.
  924. Returns:
  925. The range of numbers.
  926. """
  927. from .sequence import ArrayVar
  928. return ArrayVar.range(first_endpoint, second_endpoint, step)
  929. def __bool__(self) -> bool:
  930. """Raise exception if using Var in a boolean context.
  931. Raises:
  932. VarTypeError: when attempting to bool-ify the Var.
  933. """
  934. raise VarTypeError(
  935. f"Cannot convert Var {str(self)!r} to bool for use with `if`, `and`, `or`, and `not`. "
  936. "Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
  937. )
  938. def __iter__(self) -> Any:
  939. """Raise exception if using Var in an iterable context.
  940. Raises:
  941. VarTypeError: when attempting to iterate over the Var.
  942. """
  943. raise VarTypeError(
  944. f"Cannot iterate over Var {str(self)!r}. Instead use `rx.foreach`."
  945. )
  946. def __contains__(self, _: Any) -> Var:
  947. """Override the 'in' operator to alert the user that it is not supported.
  948. Raises:
  949. VarTypeError: the operation is not supported
  950. """
  951. raise VarTypeError(
  952. "'in' operator not supported for Var types, use Var.contains() instead."
  953. )
  954. OUTPUT = TypeVar("OUTPUT", bound=Var)
  955. VAR_SUBCLASS = TypeVar("VAR_SUBCLASS", bound=Var)
  956. VAR_INSIDE = TypeVar("VAR_INSIDE")
  957. class ToOperation:
  958. """A var operation that converts a var to another type."""
  959. def __getattr__(self, name: str) -> Any:
  960. """Get an attribute of the var.
  961. Args:
  962. name: The name of the attribute.
  963. Returns:
  964. The attribute of the var.
  965. """
  966. from .object import ObjectVar
  967. if isinstance(self, ObjectVar) and name != "_js_expr":
  968. return ObjectVar.__getattr__(self, name)
  969. return getattr(self._original, name)
  970. def __post_init__(self):
  971. """Post initialization."""
  972. object.__delattr__(self, "_js_expr")
  973. def __hash__(self) -> int:
  974. """Calculate the hash value of the object.
  975. Returns:
  976. int: The hash value of the object.
  977. """
  978. return hash(self._original)
  979. def _get_all_var_data(self) -> VarData | None:
  980. """Get all the var data.
  981. Returns:
  982. The var data.
  983. """
  984. return VarData.merge(
  985. self._original._get_all_var_data(),
  986. self._var_data, # type: ignore
  987. )
  988. @classmethod
  989. def create(
  990. cls,
  991. value: Var,
  992. _var_type: GenericType | None = None,
  993. _var_data: VarData | None = None,
  994. ):
  995. """Create a ToOperation.
  996. Args:
  997. value: The value of the var.
  998. _var_type: The type of the Var.
  999. _var_data: Additional hooks and imports associated with the Var.
  1000. Returns:
  1001. The ToOperation.
  1002. """
  1003. return cls(
  1004. _js_expr="", # type: ignore
  1005. _var_data=_var_data, # type: ignore
  1006. _var_type=_var_type or cls._default_var_type, # type: ignore
  1007. _original=value, # type: ignore
  1008. )
  1009. class LiteralVar(Var):
  1010. """Base class for immutable literal vars."""
  1011. def __init_subclass__(cls, **kwargs):
  1012. """Initialize the subclass.
  1013. Args:
  1014. **kwargs: Additional keyword arguments.
  1015. Raises:
  1016. TypeError: If the LiteralVar subclass does not have a corresponding Var subclass.
  1017. """
  1018. super().__init_subclass__(**kwargs)
  1019. bases = cls.__bases__
  1020. bases_normalized = [
  1021. base if inspect.isclass(base) else get_origin(base) for base in bases
  1022. ]
  1023. possible_bases = [
  1024. base
  1025. for base in bases_normalized
  1026. if issubclass(base, Var) and base != LiteralVar
  1027. ]
  1028. if not possible_bases:
  1029. raise TypeError(
  1030. f"LiteralVar subclass {cls} must have a base class that is a subclass of Var and not LiteralVar."
  1031. )
  1032. var_subclasses = [
  1033. var_subclass
  1034. for var_subclass in _var_subclasses
  1035. if var_subclass.var_subclass in possible_bases
  1036. ]
  1037. if not var_subclasses:
  1038. raise TypeError(
  1039. f"LiteralVar {cls} must have a base class annotated with `python_types`."
  1040. )
  1041. if len(var_subclasses) != 1:
  1042. raise TypeError(
  1043. f"LiteralVar {cls} must have exactly one base class annotated with `python_types`."
  1044. )
  1045. var_subclass = var_subclasses[0]
  1046. # Remove the old subclass, happens because __init_subclass__ is called twice
  1047. # for each subclass. This is because of __slots__ in dataclasses.
  1048. for var_literal_subclass in list(_var_literal_subclasses):
  1049. if var_literal_subclass[1] is var_subclass:
  1050. _var_literal_subclasses.remove(var_literal_subclass)
  1051. _var_literal_subclasses.append((cls, var_subclass))
  1052. @classmethod
  1053. def create(
  1054. cls,
  1055. value: Any,
  1056. _var_data: VarData | None = None,
  1057. ) -> Var:
  1058. """Create a var from a value.
  1059. Args:
  1060. value: The value to create the var from.
  1061. _var_data: Additional hooks and imports associated with the Var.
  1062. Returns:
  1063. The var.
  1064. Raises:
  1065. TypeError: If the value is not a supported type for LiteralVar.
  1066. """
  1067. from .object import LiteralObjectVar
  1068. from .sequence import LiteralStringVar
  1069. if isinstance(value, Var):
  1070. if _var_data is None:
  1071. return value
  1072. return value._replace(merge_var_data=_var_data)
  1073. for literal_subclass, var_subclass in _var_literal_subclasses[::-1]:
  1074. if isinstance(value, var_subclass.python_types):
  1075. return literal_subclass.create(value, _var_data=_var_data)
  1076. from reflex.event import EventHandler
  1077. from reflex.utils.format import get_event_handler_parts
  1078. if isinstance(value, EventHandler):
  1079. return Var(_js_expr=".".join(filter(None, get_event_handler_parts(value))))
  1080. serialized_value = serializers.serialize(value)
  1081. if serialized_value is not None:
  1082. if isinstance(serialized_value, dict):
  1083. return LiteralObjectVar.create(
  1084. serialized_value,
  1085. _var_type=type(value),
  1086. _var_data=_var_data,
  1087. )
  1088. if isinstance(serialized_value, str):
  1089. return LiteralStringVar.create(
  1090. serialized_value, _var_type=type(value), _var_data=_var_data
  1091. )
  1092. return LiteralVar.create(serialized_value, _var_data=_var_data)
  1093. if isinstance(value, Base):
  1094. # get the fields of the pydantic class
  1095. fields = value.__fields__.keys()
  1096. one_level_dict = {field: getattr(value, field) for field in fields}
  1097. return LiteralObjectVar.create(
  1098. {
  1099. field: value
  1100. for field, value in one_level_dict.items()
  1101. if not callable(value)
  1102. },
  1103. _var_type=type(value),
  1104. _var_data=_var_data,
  1105. )
  1106. if dataclasses.is_dataclass(value) and not isinstance(value, type):
  1107. return LiteralObjectVar.create(
  1108. {
  1109. k: (None if callable(v) else v)
  1110. for k, v in dataclasses.asdict(value).items()
  1111. },
  1112. _var_type=type(value),
  1113. _var_data=_var_data,
  1114. )
  1115. raise TypeError(
  1116. f"Unsupported type {type(value)} for LiteralVar. Tried to create a LiteralVar from {value}."
  1117. )
  1118. def __post_init__(self):
  1119. """Post-initialize the var."""
  1120. def json(self) -> str:
  1121. """Serialize the var to a JSON string.
  1122. Raises:
  1123. NotImplementedError: If the method is not implemented.
  1124. """
  1125. raise NotImplementedError(
  1126. "LiteralVar subclasses must implement the json method."
  1127. )
  1128. @serializers.serializer
  1129. def serialize_literal(value: LiteralVar):
  1130. """Serialize a Literal type.
  1131. Args:
  1132. value: The Literal to serialize.
  1133. Returns:
  1134. The serialized Literal.
  1135. """
  1136. return value._var_value
  1137. def get_python_literal(value: Union[LiteralVar, Any]) -> Any | None:
  1138. """Get the Python literal value.
  1139. Args:
  1140. value: The value to get the Python literal value of.
  1141. Returns:
  1142. The Python literal value.
  1143. """
  1144. if isinstance(value, LiteralVar):
  1145. return value._var_value
  1146. if isinstance(value, Var):
  1147. return None
  1148. return value
  1149. def validate_arg(type_hint: GenericType) -> Callable[[Any], bool]:
  1150. """Create a validator for an argument.
  1151. Args:
  1152. type_hint: The type hint of the argument.
  1153. Returns:
  1154. The validator.
  1155. """
  1156. def validate(value: Any):
  1157. return True
  1158. return validate
  1159. P = ParamSpec("P")
  1160. T = TypeVar("T")
  1161. V1 = TypeVar("V1")
  1162. V2 = TypeVar("V2")
  1163. V3 = TypeVar("V3")
  1164. V4 = TypeVar("V4")
  1165. V5 = TypeVar("V5")
  1166. class TypeComputer(Protocol):
  1167. """A protocol for type computers."""
  1168. def __call__(self, *args: Var) -> Tuple[GenericType, Union[TypeComputer, None]]:
  1169. """Compute the type of the operation.
  1170. Args:
  1171. *args: The arguments to compute the type of.
  1172. """
  1173. ...
  1174. @overload
  1175. def var_operation(
  1176. func: Callable[[], CustomVarOperationReturn[T]],
  1177. ) -> ArgsFunctionOperation[ReflexCallable[[], T]]: ...
  1178. @overload
  1179. def var_operation(
  1180. func: Callable[[Var[V1]], CustomVarOperationReturn[T]],
  1181. ) -> ArgsFunctionOperation[ReflexCallable[[V1], T]]: ...
  1182. @overload
  1183. def var_operation(
  1184. func: Callable[[Var[V1], Var[V2]], CustomVarOperationReturn[T]],
  1185. ) -> ArgsFunctionOperation[ReflexCallable[[V1, V2], T]]: ...
  1186. @overload
  1187. def var_operation(
  1188. func: Callable[[Var[V1], Var[V2], Var[V3]], CustomVarOperationReturn[T]],
  1189. ) -> ArgsFunctionOperation[ReflexCallable[[V1, V2, V3], T]]: ...
  1190. @overload
  1191. def var_operation(
  1192. func: Callable[[Var[V1], Var[V2], Var[V3], Var[V4]], CustomVarOperationReturn[T]],
  1193. ) -> ArgsFunctionOperation[ReflexCallable[[V1, V2, V3, V4], T]]: ...
  1194. @overload
  1195. def var_operation(
  1196. func: Callable[
  1197. [Var[V1], Var[V2], Var[V3], Var[V4], Var[V5]],
  1198. CustomVarOperationReturn[T],
  1199. ],
  1200. ) -> ArgsFunctionOperation[ReflexCallable[[V1, V2, V3, V4, V5], T]]: ...
  1201. def var_operation(
  1202. func: Callable[..., CustomVarOperationReturn[T]],
  1203. ) -> ArgsFunctionOperation[ReflexCallable[..., T]]:
  1204. """Decorator for creating a var operation.
  1205. Example:
  1206. ```python
  1207. @var_operation
  1208. def add(a: Var[int], b: Var[int]):
  1209. return custom_var_operation(f"{a} + {b}")
  1210. ```
  1211. Args:
  1212. func: The function to decorate.
  1213. Returns:
  1214. The decorated function.
  1215. Raises:
  1216. TypeError: If the function has keyword-only arguments or arguments without Var type hints.
  1217. """
  1218. from .function import ArgsFunctionOperation, ReflexCallable
  1219. func_name = func.__name__
  1220. func_arg_spec = inspect.getfullargspec(func)
  1221. if func_arg_spec.kwonlyargs:
  1222. raise TypeError(f"Function {func_name} cannot have keyword-only arguments.")
  1223. if func_arg_spec.varargs:
  1224. raise TypeError(f"Function {func_name} cannot have variable arguments.")
  1225. arg_names = func_arg_spec.args
  1226. type_hints = get_type_hints(func)
  1227. if not all(
  1228. (get_origin((type_hint := type_hints.get(arg_name, Any))) or type_hint) is Var
  1229. and len(get_args(type_hint)) <= 1
  1230. for arg_name in arg_names
  1231. ):
  1232. raise TypeError(
  1233. f"Function {func_name} must have type hints of the form `Var[Type]`."
  1234. )
  1235. args_with_type_hints = tuple(
  1236. (arg_name, (args[0] if (args := get_args(type_hints[arg_name])) else Any))
  1237. for arg_name in arg_names
  1238. )
  1239. arg_vars = tuple(
  1240. (
  1241. Var("_" + arg_name, _var_type=arg_python_type)
  1242. if not isinstance(arg_python_type, TypeVar)
  1243. else Var("_" + arg_name)
  1244. )
  1245. for arg_name, arg_python_type in args_with_type_hints
  1246. )
  1247. custom_operation_return = func(*arg_vars)
  1248. args_operation = ArgsFunctionOperation.create(
  1249. tuple(map(str, arg_vars)),
  1250. custom_operation_return,
  1251. validators=tuple(
  1252. validate_arg(type_hints.get(arg_name, Any)) for arg_name in arg_names
  1253. ),
  1254. function_name=func_name,
  1255. type_computer=custom_operation_return._type_computer,
  1256. _var_type=ReflexCallable[
  1257. tuple(arg_python_type for _, arg_python_type in args_with_type_hints), # type: ignore
  1258. custom_operation_return._var_type,
  1259. ],
  1260. )
  1261. return args_operation
  1262. def figure_out_type(value: Any) -> types.GenericType:
  1263. """Figure out the type of the value.
  1264. Args:
  1265. value: The value to figure out the type of.
  1266. Returns:
  1267. The type of the value.
  1268. """
  1269. if isinstance(value, Var):
  1270. return value._var_type
  1271. type_ = type(value)
  1272. if has_args(type_):
  1273. return type_
  1274. if isinstance(value, list):
  1275. return List[unionize(*(figure_out_type(v) for v in value))]
  1276. if isinstance(value, set):
  1277. return Set[unionize(*(figure_out_type(v) for v in value))]
  1278. if isinstance(value, tuple):
  1279. return Tuple[unionize(*(figure_out_type(v) for v in value)), ...]
  1280. if isinstance(value, dict):
  1281. return Dict[
  1282. unionize(*(figure_out_type(k) for k in value)),
  1283. unionize(*(figure_out_type(v) for v in value.values())),
  1284. ]
  1285. return type(value)
  1286. class cached_property_no_lock(functools.cached_property):
  1287. """A special version of functools.cached_property that does not use a lock."""
  1288. def __init__(self, func):
  1289. """Initialize the cached_property_no_lock.
  1290. Args:
  1291. func: The function to cache.
  1292. """
  1293. super().__init__(func)
  1294. self.lock = contextlib.nullcontext()
  1295. class CachedVarOperation:
  1296. """Base class for cached var operations to lower boilerplate code."""
  1297. def __post_init__(self):
  1298. """Post-initialize the CachedVarOperation."""
  1299. object.__delattr__(self, "_js_expr")
  1300. def __getattr__(self, name: str) -> Any:
  1301. """Get an attribute of the var.
  1302. Args:
  1303. name: The name of the attribute.
  1304. Returns:
  1305. The attribute.
  1306. """
  1307. if name == "_js_expr":
  1308. return self._cached_var_name
  1309. parent_classes = inspect.getmro(self.__class__)
  1310. next_class = parent_classes[parent_classes.index(CachedVarOperation) + 1]
  1311. return next_class.__getattr__(self, name) # type: ignore
  1312. def _get_all_var_data(self) -> VarData | None:
  1313. """Get all VarData associated with the Var.
  1314. Returns:
  1315. The VarData of the components and all of its children.
  1316. """
  1317. return self._cached_get_all_var_data
  1318. @cached_property_no_lock
  1319. def _cached_get_all_var_data(self) -> VarData | None:
  1320. """Get the cached VarData.
  1321. Returns:
  1322. The cached VarData.
  1323. """
  1324. return VarData.merge(
  1325. *map(
  1326. lambda value: (
  1327. value._get_all_var_data() if isinstance(value, Var) else None
  1328. ),
  1329. map(
  1330. lambda field: getattr(self, field.name),
  1331. dataclasses.fields(self), # type: ignore
  1332. ),
  1333. ),
  1334. self._var_data,
  1335. )
  1336. def __hash__(self) -> int:
  1337. """Calculate the hash of the object.
  1338. Returns:
  1339. The hash of the object.
  1340. """
  1341. return hash(
  1342. (
  1343. self.__class__.__name__,
  1344. *[
  1345. getattr(self, field.name)
  1346. for field in dataclasses.fields(self) # type: ignore
  1347. if field.name not in ["_js_expr", "_var_data", "_var_type"]
  1348. ],
  1349. )
  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((self.__class__.__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 = dict(
  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 {str(self)} 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: bool = False,
  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 False and interval is not None:
  1832. raise ValueError("Cannot set update interval without caching.")
  1833. if cache is False and (deps is not None or auto_deps is False):
  1834. raise VarDependencyError("Cannot track dependencies without caching.")
  1835. if fget is not None:
  1836. return ComputedVar(fget, cache=cache)
  1837. def wrapper(fget: Callable[[BASE_STATE], Any]) -> ComputedVar:
  1838. return ComputedVar(
  1839. fget,
  1840. initial_value=initial_value,
  1841. cache=cache,
  1842. deps=deps,
  1843. auto_deps=auto_deps,
  1844. interval=interval,
  1845. backend=backend,
  1846. **kwargs,
  1847. )
  1848. return wrapper
  1849. RETURN = TypeVar("RETURN")
  1850. @dataclasses.dataclass(
  1851. eq=False,
  1852. frozen=True,
  1853. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1854. )
  1855. class CustomVarOperationReturn(Var[RETURN]):
  1856. """Base class for custom var operations."""
  1857. _type_computer: Optional[TypeComputer] = dataclasses.field(default=None)
  1858. @classmethod
  1859. def create(
  1860. cls,
  1861. js_expression: str,
  1862. _var_type: Type[RETURN] | None = None,
  1863. _type_computer: Optional[TypeComputer] = None,
  1864. _var_data: VarData | None = None,
  1865. ) -> CustomVarOperationReturn[RETURN]:
  1866. """Create a CustomVarOperation.
  1867. Args:
  1868. js_expression: The JavaScript expression to evaluate.
  1869. _var_type: The type of the var.
  1870. _type_computer: A function to compute the type of the var given the arguments.
  1871. _var_data: Additional hooks and imports associated with the Var.
  1872. Returns:
  1873. The CustomVarOperation.
  1874. """
  1875. return CustomVarOperationReturn(
  1876. _js_expr=js_expression,
  1877. _var_type=_var_type or Any,
  1878. _type_computer=_type_computer,
  1879. _var_data=_var_data,
  1880. )
  1881. def var_operation_return(
  1882. js_expression: str,
  1883. var_type: Type[RETURN] | None = None,
  1884. type_computer: Optional[TypeComputer] = None,
  1885. var_data: VarData | None = None,
  1886. ) -> CustomVarOperationReturn[RETURN]:
  1887. """Shortcut for creating a CustomVarOperationReturn.
  1888. Args:
  1889. js_expression: The JavaScript expression to evaluate.
  1890. var_type: The type of the var.
  1891. type_computer: A function to compute the type of the var given the arguments.
  1892. var_data: Additional hooks and imports associated with the Var.
  1893. Returns:
  1894. The CustomVarOperationReturn.
  1895. """
  1896. return CustomVarOperationReturn.create(
  1897. js_expression=js_expression,
  1898. _var_type=var_type,
  1899. _type_computer=type_computer,
  1900. _var_data=var_data,
  1901. )
  1902. @dataclasses.dataclass(
  1903. eq=False,
  1904. frozen=True,
  1905. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1906. )
  1907. class CustomVarOperation(CachedVarOperation, Var[T]):
  1908. """Base class for custom var operations."""
  1909. _name: str = dataclasses.field(default="")
  1910. _args: Tuple[Tuple[str, Var], ...] = dataclasses.field(default_factory=tuple)
  1911. _return: CustomVarOperationReturn[T] = dataclasses.field(
  1912. default_factory=lambda: CustomVarOperationReturn.create("")
  1913. )
  1914. @cached_property_no_lock
  1915. def _cached_var_name(self) -> str:
  1916. """Get the cached var name.
  1917. Returns:
  1918. The cached var name.
  1919. """
  1920. return str(self._return)
  1921. @cached_property_no_lock
  1922. def _cached_get_all_var_data(self) -> VarData | None:
  1923. """Get the cached VarData.
  1924. Returns:
  1925. The cached VarData.
  1926. """
  1927. return VarData.merge(
  1928. *map(
  1929. lambda arg: arg[1]._get_all_var_data(),
  1930. self._args,
  1931. ),
  1932. self._return._get_all_var_data(),
  1933. self._var_data,
  1934. )
  1935. @classmethod
  1936. def create(
  1937. cls,
  1938. name: str,
  1939. args: Tuple[Tuple[str, Var], ...],
  1940. return_var: CustomVarOperationReturn[T],
  1941. _var_data: VarData | None = None,
  1942. ) -> CustomVarOperation[T]:
  1943. """Create a CustomVarOperation.
  1944. Args:
  1945. name: The name of the operation.
  1946. args: The arguments to the operation.
  1947. return_var: The return var.
  1948. _var_data: Additional hooks and imports associated with the Var.
  1949. Returns:
  1950. The CustomVarOperation.
  1951. """
  1952. return CustomVarOperation(
  1953. _js_expr="",
  1954. _var_type=return_var._var_type,
  1955. _var_data=_var_data,
  1956. _name=name,
  1957. _args=args,
  1958. _return=return_var,
  1959. )
  1960. class NoneVar(Var[None], python_types=type(None)):
  1961. """A var representing None."""
  1962. @dataclasses.dataclass(
  1963. eq=False,
  1964. frozen=True,
  1965. **{"slots": True} if sys.version_info >= (3, 10) else {},
  1966. )
  1967. class LiteralNoneVar(LiteralVar, NoneVar):
  1968. """A var representing None."""
  1969. _var_value: None = None
  1970. def json(self) -> str:
  1971. """Serialize the var to a JSON string.
  1972. Returns:
  1973. The JSON string.
  1974. """
  1975. return "null"
  1976. @classmethod
  1977. def create(
  1978. cls,
  1979. value: None = None,
  1980. _var_data: VarData | None = None,
  1981. ) -> LiteralNoneVar:
  1982. """Create a var from a value.
  1983. Args:
  1984. value: The value of the var. Must be None. Existed for compatibility with LiteralVar.
  1985. _var_data: Additional hooks and imports associated with the Var.
  1986. Returns:
  1987. The var.
  1988. """
  1989. return LiteralNoneVar(
  1990. _js_expr="null",
  1991. _var_type=None,
  1992. _var_data=_var_data,
  1993. )
  1994. def get_to_operation(var_subclass: Type[Var]) -> Type[ToOperation]:
  1995. """Get the ToOperation class for a given Var subclass.
  1996. Args:
  1997. var_subclass: The Var subclass.
  1998. Returns:
  1999. The ToOperation class.
  2000. Raises:
  2001. ValueError: If the ToOperation class cannot be found.
  2002. """
  2003. possible_classes = [
  2004. saved_var_subclass.to_var_subclass
  2005. for saved_var_subclass in _var_subclasses
  2006. if saved_var_subclass.var_subclass is var_subclass
  2007. ]
  2008. if not possible_classes:
  2009. raise ValueError(f"Could not find ToOperation for {var_subclass}.")
  2010. return possible_classes[0]
  2011. @dataclasses.dataclass(
  2012. eq=False,
  2013. frozen=True,
  2014. **{"slots": True} if sys.version_info >= (3, 10) else {},
  2015. )
  2016. class StateOperation(CachedVarOperation, Var):
  2017. """A var operation that accesses a field on an object."""
  2018. _state_name: str = dataclasses.field(default="")
  2019. _field: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  2020. @cached_property_no_lock
  2021. def _cached_var_name(self) -> str:
  2022. """Get the cached var name.
  2023. Returns:
  2024. The cached var name.
  2025. """
  2026. return f"{str(self._state_name)}.{str(self._field)}"
  2027. def __getattr__(self, name: str) -> Any:
  2028. """Get an attribute of the var.
  2029. Args:
  2030. name: The name of the attribute.
  2031. Returns:
  2032. The attribute.
  2033. """
  2034. if name == "_js_expr":
  2035. return self._cached_var_name
  2036. return getattr(self._field, name)
  2037. @classmethod
  2038. def create(
  2039. cls,
  2040. state_name: str,
  2041. field: Var,
  2042. _var_data: VarData | None = None,
  2043. ) -> StateOperation:
  2044. """Create a DotOperation.
  2045. Args:
  2046. state_name: The name of the state.
  2047. field: The field of the state.
  2048. _var_data: Additional hooks and imports associated with the Var.
  2049. Returns:
  2050. The DotOperation.
  2051. """
  2052. return StateOperation(
  2053. _js_expr="",
  2054. _var_type=field._var_type,
  2055. _var_data=_var_data,
  2056. _state_name=state_name,
  2057. _field=field,
  2058. )
  2059. def get_uuid_string_var() -> Var:
  2060. """Return a Var that generates a single memoized UUID via .web/utils/state.js.
  2061. useMemo with an empty dependency array ensures that the generated UUID is
  2062. consistent across re-renders of the component.
  2063. Returns:
  2064. A Var that generates a UUID at runtime.
  2065. """
  2066. from reflex.utils.imports import ImportVar
  2067. from reflex.vars import Var
  2068. unique_uuid_var = get_unique_variable_name()
  2069. unique_uuid_var_data = VarData(
  2070. imports={
  2071. f"$/{constants.Dirs.STATE_PATH}": {ImportVar(tag="generateUUID")}, # type: ignore
  2072. "react": "useMemo",
  2073. },
  2074. hooks={f"const {unique_uuid_var} = useMemo(generateUUID, [])": None},
  2075. )
  2076. return Var(
  2077. _js_expr=unique_uuid_var,
  2078. _var_type=str,
  2079. _var_data=unique_uuid_var_data,
  2080. )
  2081. # Set of unique variable names.
  2082. USED_VARIABLES = set()
  2083. def get_unique_variable_name() -> str:
  2084. """Get a unique variable name.
  2085. Returns:
  2086. The unique variable name.
  2087. """
  2088. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  2089. if name not in USED_VARIABLES:
  2090. USED_VARIABLES.add(name)
  2091. return name
  2092. return get_unique_variable_name()
  2093. # Compile regex for finding reflex var tags.
  2094. _decode_var_pattern_re = (
  2095. rf"{constants.REFLEX_VAR_OPENING_TAG}(.*?){constants.REFLEX_VAR_CLOSING_TAG}"
  2096. )
  2097. _decode_var_pattern = re.compile(_decode_var_pattern_re, flags=re.DOTALL)
  2098. # Defined global immutable vars.
  2099. _global_vars: Dict[int, Var] = {}
  2100. def _extract_var_data(value: Iterable) -> list[VarData | None]:
  2101. """Extract the var imports and hooks from an iterable containing a Var.
  2102. Args:
  2103. value: The iterable to extract the VarData from
  2104. Returns:
  2105. The extracted VarDatas.
  2106. """
  2107. from reflex.style import Style
  2108. from reflex.vars import Var
  2109. var_datas = []
  2110. with contextlib.suppress(TypeError):
  2111. for sub in value:
  2112. if isinstance(sub, Var):
  2113. var_datas.append(sub._var_data)
  2114. elif not isinstance(sub, str):
  2115. # Recurse into dict values.
  2116. if hasattr(sub, "values") and callable(sub.values):
  2117. var_datas.extend(_extract_var_data(sub.values()))
  2118. # Recurse into iterable values (or dict keys).
  2119. var_datas.extend(_extract_var_data(sub))
  2120. # Style objects should already have _var_data.
  2121. if isinstance(value, Style):
  2122. var_datas.append(value._var_data)
  2123. else:
  2124. # Recurse when value is a dict itself.
  2125. values = getattr(value, "values", None)
  2126. if callable(values):
  2127. var_datas.extend(_extract_var_data(values()))
  2128. return var_datas
  2129. # These names were changed in reflex 0.3.0
  2130. REPLACED_NAMES = {
  2131. "full_name": "_var_full_name",
  2132. "name": "_js_expr",
  2133. "state": "_var_data.state",
  2134. "type_": "_var_type",
  2135. "is_local": "_var_is_local",
  2136. "is_string": "_var_is_string",
  2137. "set_state": "_var_set_state",
  2138. "deps": "_deps",
  2139. }
  2140. dispatchers: Dict[GenericType, Callable[[Var], Var]] = {}
  2141. def transform(fn: Callable[[Var], Var]) -> Callable[[Var], Var]:
  2142. """Register a function to transform a Var.
  2143. Args:
  2144. fn: The function to register.
  2145. Returns:
  2146. The decorator.
  2147. Raises:
  2148. TypeError: If the return type of the function is not a Var.
  2149. TypeError: If the Var return type does not have a generic type.
  2150. ValueError: If a function for the generic type is already registered.
  2151. """
  2152. return_type = fn.__annotations__["return"]
  2153. origin = get_origin(return_type)
  2154. if origin is not Var:
  2155. raise TypeError(
  2156. f"Expected return type of {fn.__name__} to be a Var, got {origin}."
  2157. )
  2158. generic_args = get_args(return_type)
  2159. if not generic_args:
  2160. raise TypeError(
  2161. f"Expected Var return type of {fn.__name__} to have a generic type."
  2162. )
  2163. generic_type = get_origin(generic_args[0]) or generic_args[0]
  2164. if generic_type in dispatchers:
  2165. raise ValueError(f"Function for {generic_type} already registered.")
  2166. dispatchers[generic_type] = fn
  2167. return fn
  2168. def generic_type_to_actual_type_map(
  2169. generic_type: GenericType, actual_type: GenericType
  2170. ) -> Dict[TypeVar, GenericType]:
  2171. """Map the generic type to the actual type.
  2172. Args:
  2173. generic_type: The generic type.
  2174. actual_type: The actual type.
  2175. Returns:
  2176. The mapping of type variables to actual types.
  2177. Raises:
  2178. TypeError: If the generic type and actual type do not match.
  2179. TypeError: If the number of generic arguments and actual arguments do not match.
  2180. """
  2181. generic_origin = get_origin(generic_type) or generic_type
  2182. actual_origin = get_origin(actual_type) or actual_type
  2183. if generic_origin is not actual_origin:
  2184. if isinstance(generic_origin, TypeVar):
  2185. return {generic_origin: actual_origin}
  2186. raise TypeError(
  2187. f"Type mismatch: expected {generic_origin}, got {actual_origin}."
  2188. )
  2189. generic_args = get_args(generic_type)
  2190. actual_args = get_args(actual_type)
  2191. if len(generic_args) != len(actual_args):
  2192. raise TypeError(
  2193. f"Number of generic arguments mismatch: expected {len(generic_args)}, got {len(actual_args)}."
  2194. )
  2195. # call recursively for nested generic types and merge the results
  2196. return {
  2197. k: v
  2198. for generic_arg, actual_arg in zip(generic_args, actual_args)
  2199. for k, v in generic_type_to_actual_type_map(generic_arg, actual_arg).items()
  2200. }
  2201. def resolve_generic_type_with_mapping(
  2202. generic_type: GenericType, type_mapping: Dict[TypeVar, GenericType]
  2203. ):
  2204. """Resolve a generic type with a type mapping.
  2205. Args:
  2206. generic_type: The generic type.
  2207. type_mapping: The type mapping.
  2208. Returns:
  2209. The resolved generic type.
  2210. """
  2211. if isinstance(generic_type, TypeVar):
  2212. return type_mapping.get(generic_type, generic_type)
  2213. generic_origin = get_origin(generic_type) or generic_type
  2214. generic_args = get_args(generic_type)
  2215. if not generic_args:
  2216. return generic_type
  2217. mapping_for_older_python = {
  2218. list: List,
  2219. set: Set,
  2220. dict: Dict,
  2221. tuple: Tuple,
  2222. frozenset: FrozenSet,
  2223. }
  2224. return mapping_for_older_python.get(generic_origin, generic_origin)[
  2225. tuple(
  2226. resolve_generic_type_with_mapping(arg, type_mapping) for arg in generic_args
  2227. )
  2228. ]
  2229. def resolve_arg_type_from_return_type(
  2230. arg_type: GenericType, return_type: GenericType, actual_return_type: GenericType
  2231. ) -> GenericType:
  2232. """Resolve the argument type from the return type.
  2233. Args:
  2234. arg_type: The argument type.
  2235. return_type: The return type.
  2236. actual_return_type: The requested return type.
  2237. Returns:
  2238. The argument type without the generics that are resolved.
  2239. """
  2240. return resolve_generic_type_with_mapping(
  2241. arg_type, generic_type_to_actual_type_map(return_type, actual_return_type)
  2242. )
  2243. def dispatch(
  2244. field_name: str,
  2245. var_data: VarData,
  2246. result_var_type: GenericType,
  2247. existing_var: Var | None = None,
  2248. ) -> Var:
  2249. """Dispatch a Var to the appropriate transformation function.
  2250. Args:
  2251. field_name: The name of the field.
  2252. var_data: The VarData associated with the Var.
  2253. result_var_type: The type of the Var.
  2254. existing_var: The existing Var to transform. Optional.
  2255. Returns:
  2256. The transformed Var.
  2257. Raises:
  2258. TypeError: If the return type of the function is not a Var.
  2259. TypeError: If the Var return type does not have a generic type.
  2260. TypeError: If the first argument of the function is not a Var.
  2261. TypeError: If the first argument of the function does not have a generic type
  2262. """
  2263. result_origin_var_type = get_origin(result_var_type) or result_var_type
  2264. if result_origin_var_type in dispatchers:
  2265. fn = dispatchers[result_origin_var_type]
  2266. fn_first_arg_type = list(inspect.signature(fn).parameters.values())[
  2267. 0
  2268. ].annotation
  2269. fn_return = inspect.signature(fn).return_annotation
  2270. fn_return_origin = get_origin(fn_return) or fn_return
  2271. if fn_return_origin is not Var:
  2272. raise TypeError(
  2273. f"Expected return type of {fn.__name__} to be a Var, got {fn_return}."
  2274. )
  2275. fn_return_generic_args = get_args(fn_return)
  2276. if not fn_return_generic_args:
  2277. raise TypeError(f"Expected generic type of {fn_return} to be a type.")
  2278. arg_origin = get_origin(fn_first_arg_type) or fn_first_arg_type
  2279. if arg_origin is not Var:
  2280. raise TypeError(
  2281. f"Expected first argument of {fn.__name__} to be a Var, got {fn_first_arg_type}."
  2282. )
  2283. arg_generic_args = get_args(fn_first_arg_type)
  2284. if not arg_generic_args:
  2285. raise TypeError(
  2286. f"Expected generic type of {fn_first_arg_type} to be a type."
  2287. )
  2288. arg_type = arg_generic_args[0]
  2289. fn_return_type = fn_return_generic_args[0]
  2290. var = (
  2291. Var(
  2292. field_name,
  2293. _var_data=var_data,
  2294. _var_type=resolve_arg_type_from_return_type(
  2295. arg_type, fn_return_type, result_var_type
  2296. ),
  2297. ).guess_type()
  2298. if existing_var is None
  2299. else existing_var._replace(
  2300. _var_type=resolve_arg_type_from_return_type(
  2301. arg_type, fn_return_type, result_var_type
  2302. ),
  2303. _var_data=var_data,
  2304. _js_expr=field_name,
  2305. ).guess_type()
  2306. )
  2307. return fn(var)
  2308. if existing_var is not None:
  2309. return existing_var._replace(
  2310. _js_expr=field_name,
  2311. _var_data=var_data,
  2312. _var_type=result_var_type,
  2313. ).guess_type()
  2314. return Var(
  2315. field_name,
  2316. _var_data=var_data,
  2317. _var_type=result_var_type,
  2318. ).guess_type()
  2319. V = TypeVar("V")
  2320. BASE_TYPE = TypeVar("BASE_TYPE", bound=Base)
  2321. class Field(Generic[T]):
  2322. """Shadow class for Var to allow for type hinting in the IDE."""
  2323. def __set__(self, instance, value: T):
  2324. """Set the Var.
  2325. Args:
  2326. instance: The instance of the class setting the Var.
  2327. value: The value to set the Var to.
  2328. """
  2329. @overload
  2330. def __get__(self: Field[bool], instance: None, owner) -> BooleanVar: ...
  2331. @overload
  2332. def __get__(self: Field[int], instance: None, owner) -> NumberVar: ...
  2333. @overload
  2334. def __get__(self: Field[str], instance: None, owner) -> StringVar: ...
  2335. @overload
  2336. def __get__(self: Field[None], instance: None, owner) -> NoneVar: ...
  2337. @overload
  2338. def __get__(
  2339. self: Field[List[V]] | Field[Set[V]] | Field[Tuple[V, ...]],
  2340. instance: None,
  2341. owner,
  2342. ) -> ArrayVar[List[V]]: ...
  2343. @overload
  2344. def __get__(
  2345. self: Field[Dict[str, V]], instance: None, owner
  2346. ) -> ObjectVar[Dict[str, V]]: ...
  2347. @overload
  2348. def __get__(
  2349. self: Field[BASE_TYPE], instance: None, owner
  2350. ) -> ObjectVar[BASE_TYPE]: ...
  2351. @overload
  2352. def __get__(self, instance: None, owner) -> Var[T]: ...
  2353. @overload
  2354. def __get__(self, instance, owner) -> T: ...
  2355. def __get__(self, instance, owner): # type: ignore
  2356. """Get the Var.
  2357. Args:
  2358. instance: The instance of the class accessing the Var.
  2359. owner: The class that the Var is attached to.
  2360. """
  2361. def field(value: T) -> Field[T]:
  2362. """Create a Field with a value.
  2363. Args:
  2364. value: The value of the Field.
  2365. Returns:
  2366. The Field.
  2367. """
  2368. return value # type: ignore
  2369. def and_operation(a: Var | Any, b: Var | Any) -> Var:
  2370. """Perform a logical AND operation on two variables.
  2371. Args:
  2372. a: The first variable.
  2373. b: The second variable.
  2374. Returns:
  2375. The result of the logical AND operation.
  2376. """
  2377. return _and_operation(a, b) # type: ignore
  2378. @var_operation
  2379. def _and_operation(a: Var, b: Var):
  2380. """Perform a logical AND operation on two variables.
  2381. Args:
  2382. a: The first variable.
  2383. b: The second variable.
  2384. Returns:
  2385. The result of the logical AND operation.
  2386. """
  2387. def type_computer(*args: Var):
  2388. if not args:
  2389. return (ReflexCallable[[Any, Any], Any], type_computer)
  2390. if len(args) == 1:
  2391. return (
  2392. ReflexCallable[[Any], Any],
  2393. functools.partial(type_computer, args[0]),
  2394. )
  2395. return (
  2396. ReflexCallable[[], unionize(args[0]._var_type, args[1]._var_type)],
  2397. None,
  2398. )
  2399. return var_operation_return(
  2400. js_expression=f"({a} && {b})",
  2401. type_computer=type_computer,
  2402. )
  2403. def or_operation(a: Var | Any, b: Var | Any) -> Var:
  2404. """Perform a logical OR operation on two variables.
  2405. Args:
  2406. a: The first variable.
  2407. b: The second variable.
  2408. Returns:
  2409. The result of the logical OR operation.
  2410. """
  2411. return _or_operation(a, b) # type: ignore
  2412. @var_operation
  2413. def _or_operation(a: Var, b: Var):
  2414. """Perform a logical OR operation on two variables.
  2415. Args:
  2416. a: The first variable.
  2417. b: The second variable.
  2418. Returns:
  2419. The result of the logical OR operation.
  2420. """
  2421. def type_computer(*args: Var):
  2422. if not args:
  2423. return (ReflexCallable[[Any, Any], Any], type_computer)
  2424. if len(args) == 1:
  2425. return (
  2426. ReflexCallable[[Any], Any],
  2427. functools.partial(type_computer, args[0]),
  2428. )
  2429. return (
  2430. ReflexCallable[[], unionize(args[0]._var_type, args[1]._var_type)],
  2431. None,
  2432. )
  2433. return var_operation_return(
  2434. js_expression=f"({a} || {b})",
  2435. type_computer=type_computer,
  2436. )
  2437. def passthrough_unary_type_computer(no_args: GenericType) -> TypeComputer:
  2438. """Create a type computer for unary operations.
  2439. Args:
  2440. no_args: The type to return when no arguments are provided.
  2441. Returns:
  2442. The type computer.
  2443. """
  2444. def type_computer(*args: Var):
  2445. if not args:
  2446. return (no_args, type_computer)
  2447. return (ReflexCallable[[], args[0]._var_type], None)
  2448. return type_computer
  2449. def unary_type_computer(
  2450. no_args: GenericType, computer: Callable[[Var], GenericType]
  2451. ) -> TypeComputer:
  2452. """Create a type computer for unary operations.
  2453. Args:
  2454. no_args: The type to return when no arguments are provided.
  2455. computer: The function to compute the type.
  2456. Returns:
  2457. The type computer.
  2458. """
  2459. def type_computer(*args: Var):
  2460. if not args:
  2461. return (no_args, type_computer)
  2462. return (ReflexCallable[[], computer(args[0])], None)
  2463. return type_computer
  2464. def nary_type_computer(
  2465. *types: GenericType, computer: Callable[..., GenericType]
  2466. ) -> TypeComputer:
  2467. """Create a type computer for n-ary operations.
  2468. Args:
  2469. types: The types to return when no arguments are provided.
  2470. computer: The function to compute the type.
  2471. Returns:
  2472. The type computer.
  2473. """
  2474. def type_computer(*args: Var):
  2475. if len(args) != len(types):
  2476. return (
  2477. ReflexCallable[[], types[len(args)]], # type: ignore
  2478. functools.partial(type_computer, *args),
  2479. )
  2480. return (
  2481. ReflexCallable[[], computer(args)],
  2482. None,
  2483. )
  2484. return type_computer