function.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. """Immutable function vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import inspect
  5. import sys
  6. from typing import (
  7. Any,
  8. Callable,
  9. NoReturn,
  10. Optional,
  11. Sequence,
  12. Tuple,
  13. Type,
  14. Union,
  15. overload,
  16. )
  17. from typing_extensions import Concatenate, Generic, ParamSpec, TypeVar
  18. from reflex.utils import format
  19. from reflex.utils.exceptions import VarTypeError
  20. from reflex.utils.types import GenericType, Unset, get_origin
  21. from .base import (
  22. CachedVarOperation,
  23. LiteralVar,
  24. ReflexCallable,
  25. TypeComputer,
  26. Var,
  27. VarData,
  28. VarWithDefault,
  29. cached_property_no_lock,
  30. unwrap_reflex_callalbe,
  31. )
  32. P = ParamSpec("P")
  33. R = TypeVar("R")
  34. R2 = TypeVar("R2")
  35. V1 = TypeVar("V1")
  36. V2 = TypeVar("V2")
  37. V3 = TypeVar("V3")
  38. V4 = TypeVar("V4")
  39. V5 = TypeVar("V5")
  40. V6 = TypeVar("V6")
  41. CALLABLE_TYPE = TypeVar("CALLABLE_TYPE", bound=ReflexCallable, infer_variance=True)
  42. OTHER_CALLABLE_TYPE = TypeVar(
  43. "OTHER_CALLABLE_TYPE", bound=ReflexCallable, infer_variance=True
  44. )
  45. def type_is_reflex_callable(type_: Any) -> bool:
  46. """Check if a type is a ReflexCallable.
  47. Args:
  48. type_: The type to check.
  49. Returns:
  50. True if the type is a ReflexCallable.
  51. """
  52. return type_ is ReflexCallable or get_origin(type_) is ReflexCallable
  53. class FunctionVar(
  54. Var[CALLABLE_TYPE],
  55. default_type=ReflexCallable[Any, Any],
  56. is_subclass=type_is_reflex_callable,
  57. ):
  58. """Base class for immutable function vars."""
  59. @overload
  60. def partial(self) -> FunctionVar[CALLABLE_TYPE]: ...
  61. @overload
  62. def partial(
  63. self: FunctionVar[ReflexCallable[Concatenate[VarWithDefault[V1], P], R]]
  64. | FunctionVar[ReflexCallable[Concatenate[V1, P], R]],
  65. arg1: Union[V1, Var[V1]],
  66. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  67. @overload
  68. def partial(
  69. self: FunctionVar[
  70. ReflexCallable[Concatenate[VarWithDefault[V1], VarWithDefault[V2], P], R]
  71. ]
  72. | FunctionVar[ReflexCallable[Concatenate[V1, VarWithDefault[V2], P], R]]
  73. | FunctionVar[ReflexCallable[Concatenate[V1, V2, P], R]],
  74. arg1: Union[V1, Var[V1]],
  75. arg2: Union[V2, Var[V2]],
  76. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  77. @overload
  78. def partial(
  79. self: FunctionVar[
  80. ReflexCallable[
  81. Concatenate[
  82. VarWithDefault[V1], VarWithDefault[V2], VarWithDefault[V3], P
  83. ],
  84. R,
  85. ]
  86. ]
  87. | FunctionVar[
  88. ReflexCallable[
  89. Concatenate[V1, VarWithDefault[V2], VarWithDefault[V3], P], R
  90. ]
  91. ]
  92. | FunctionVar[ReflexCallable[Concatenate[V1, V2, VarWithDefault[V3], P], R]]
  93. | FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, P], R]],
  94. arg1: Union[V1, Var[V1]],
  95. arg2: Union[V2, Var[V2]],
  96. arg3: Union[V3, Var[V3]],
  97. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  98. @overload
  99. def partial(
  100. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, P], R]],
  101. arg1: Union[V1, Var[V1]],
  102. arg2: Union[V2, Var[V2]],
  103. arg3: Union[V3, Var[V3]],
  104. arg4: Union[V4, Var[V4]],
  105. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  106. @overload
  107. def partial(
  108. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, V5, P], R]],
  109. arg1: Union[V1, Var[V1]],
  110. arg2: Union[V2, Var[V2]],
  111. arg3: Union[V3, Var[V3]],
  112. arg4: Union[V4, Var[V4]],
  113. arg5: Union[V5, Var[V5]],
  114. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  115. @overload
  116. def partial(
  117. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, V5, V6, P], R]],
  118. arg1: Union[V1, Var[V1]],
  119. arg2: Union[V2, Var[V2]],
  120. arg3: Union[V3, Var[V3]],
  121. arg4: Union[V4, Var[V4]],
  122. arg5: Union[V5, Var[V5]],
  123. arg6: Union[V6, Var[V6]],
  124. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  125. @overload
  126. def partial(
  127. self: FunctionVar[ReflexCallable[P, R]], *args: Var | Any
  128. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  129. @overload
  130. def partial(self, *args: Var | Any) -> FunctionVar: ...
  131. def partial(self, *args: Var | Any) -> FunctionVar: # type: ignore
  132. """Partially apply the function with the given arguments.
  133. Args:
  134. *args: The arguments to partially apply the function with.
  135. Returns:
  136. The partially applied function.
  137. """
  138. if not args:
  139. return self
  140. args = tuple(map(LiteralVar.create, args))
  141. remaining_validators = self._pre_check(*args)
  142. partial_types, type_computer = self._partial_type(*args)
  143. if self.__call__ is self.partial:
  144. # if the default behavior is partial, we should return a new partial function
  145. return ArgsFunctionOperationBuilder.create(
  146. (),
  147. VarOperationCall.create(
  148. self,
  149. *args,
  150. Var(_js_expr="...args"),
  151. _var_type=self._return_type(*args),
  152. ),
  153. rest="args",
  154. validators=remaining_validators,
  155. type_computer=type_computer,
  156. _var_type=partial_types,
  157. )
  158. return ArgsFunctionOperation.create(
  159. (),
  160. VarOperationCall.create(
  161. self, *args, Var(_js_expr="...args"), _var_type=self._return_type(*args)
  162. ),
  163. rest="args",
  164. validators=remaining_validators,
  165. type_computer=type_computer,
  166. _var_type=partial_types,
  167. )
  168. @overload
  169. def call(self: FunctionVar[ReflexCallable[[], R]]) -> Var[R]: ...
  170. @overload
  171. def call(
  172. self: FunctionVar[ReflexCallable[[VarWithDefault[V1]], R]],
  173. arg1: Union[V1, Var[V1], Unset] = Unset(),
  174. ) -> Var[R]: ...
  175. @overload
  176. def call(
  177. self: FunctionVar[ReflexCallable[[VarWithDefault[V1], VarWithDefault[V2]], R]],
  178. arg1: Union[V1, Var[V1], Unset] = Unset(),
  179. arg2: Union[V2, Var[V2], Unset] = Unset(),
  180. ) -> Var[R]: ...
  181. @overload
  182. def call(
  183. self: FunctionVar[
  184. ReflexCallable[
  185. [VarWithDefault[V1], VarWithDefault[V2], VarWithDefault[V3]], R
  186. ]
  187. ],
  188. arg1: Union[V1, Var[V1], Unset] = Unset(),
  189. arg2: Union[V2, Var[V2], Unset] = Unset(),
  190. arg3: Union[V3, Var[V3], Unset] = Unset(),
  191. ) -> Var[R]: ...
  192. @overload
  193. def call(
  194. self: FunctionVar[ReflexCallable[[V1], R]], arg1: Union[V1, Var[V1]]
  195. ) -> Var[R]: ...
  196. @overload
  197. def call(
  198. self: FunctionVar[ReflexCallable[[V1, VarWithDefault[V2]], R]],
  199. arg1: Union[V1, Var[V1]],
  200. arg2: Union[V2, Var[V2], Unset] = Unset(),
  201. ) -> Var[R]: ...
  202. @overload
  203. def call(
  204. self: FunctionVar[
  205. ReflexCallable[[V1, VarWithDefault[V2], VarWithDefault[V3]], R]
  206. ],
  207. arg1: Union[V1, Var[V1]],
  208. arg2: Union[V2, Var[V2], Unset] = Unset(),
  209. arg3: Union[V3, Var[V3], Unset] = Unset(),
  210. ) -> Var[R]: ...
  211. @overload
  212. def call(
  213. self: FunctionVar[ReflexCallable[[V1, V2], R]],
  214. arg1: Union[V1, Var[V1]],
  215. arg2: Union[V2, Var[V2]],
  216. ) -> VarOperationCall[[V1, V2], R]: ...
  217. @overload
  218. def call(
  219. self: FunctionVar[ReflexCallable[[V1, V2, VarWithDefault[V3]], R]],
  220. arg1: Union[V1, Var[V1]],
  221. arg2: Union[V2, Var[V2]],
  222. arg3: Union[V3, Var[V3], Unset] = Unset(),
  223. ) -> Var[R]: ...
  224. @overload
  225. def call(
  226. self: FunctionVar[ReflexCallable[[V1, V2, V3], R]],
  227. arg1: Union[V1, Var[V1]],
  228. arg2: Union[V2, Var[V2]],
  229. arg3: Union[V3, Var[V3]],
  230. ) -> Var[R]: ...
  231. @overload
  232. def call(
  233. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4], R]],
  234. arg1: Union[V1, Var[V1]],
  235. arg2: Union[V2, Var[V2]],
  236. arg3: Union[V3, Var[V3]],
  237. arg4: Union[V4, Var[V4]],
  238. ) -> Var[R]: ...
  239. @overload
  240. def call(
  241. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4, V5], R]],
  242. arg1: Union[V1, Var[V1]],
  243. arg2: Union[V2, Var[V2]],
  244. arg3: Union[V3, Var[V3]],
  245. arg4: Union[V4, Var[V4]],
  246. arg5: Union[V5, Var[V5]],
  247. ) -> Var[R]: ...
  248. @overload
  249. def call(
  250. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4, V5, V6], R]],
  251. arg1: Union[V1, Var[V1]],
  252. arg2: Union[V2, Var[V2]],
  253. arg3: Union[V3, Var[V3]],
  254. arg4: Union[V4, Var[V4]],
  255. arg5: Union[V5, Var[V5]],
  256. arg6: Union[V6, Var[V6]],
  257. ) -> Var[R]: ...
  258. # Capture Any to allow for arbitrary number of arguments
  259. @overload
  260. def call(self: FunctionVar[NoReturn], *args: Var | Any) -> Var: ...
  261. def call(self, *args: Var | Any) -> Var: # pyright: ignore [reportInconsistentOverload]
  262. """Call the function with the given arguments.
  263. Args:
  264. *args: The arguments to call the function with.
  265. Returns:
  266. The function call operation.
  267. Raises:
  268. VarTypeError: If the number of arguments is invalid
  269. """
  270. required_arg_len = self._required_arg_len()
  271. arg_len = self._arg_len()
  272. if arg_len is not None:
  273. if len(args) < required_arg_len:
  274. raise VarTypeError(
  275. f"Passed {len(args)} arguments, expected at least {required_arg_len} for {self!s}"
  276. )
  277. if len(args) > arg_len:
  278. raise VarTypeError(
  279. f"Passed {len(args)} arguments, expected at most {arg_len} for {self!s}"
  280. )
  281. args = tuple(map(LiteralVar.create, args))
  282. self._pre_check(*args)
  283. return_type = self._return_type(*args)
  284. if (
  285. isinstance(self, (ArgsFunctionOperation, ArgsFunctionOperationBuilder))
  286. and self._raw_js_function
  287. ):
  288. return VarOperationCall.create(
  289. FunctionStringVar.create(
  290. self._raw_js_function,
  291. _var_type=self._var_type,
  292. _var_data=self._get_all_var_data(),
  293. ),
  294. *args,
  295. _var_type=return_type,
  296. ).guess_type()
  297. return VarOperationCall.create(self, *args, _var_type=return_type).guess_type()
  298. def chain(
  299. self: FunctionVar[ReflexCallable[P, R]],
  300. other: FunctionVar[ReflexCallable[[R], R2]]
  301. | FunctionVar[ReflexCallable[[R, VarWithDefault[Any]], R2]]
  302. | FunctionVar[
  303. ReflexCallable[[R, VarWithDefault[Any], VarWithDefault[Any]], R2]
  304. ],
  305. ) -> FunctionVar[ReflexCallable[P, R2]]:
  306. """Chain two functions together.
  307. Args:
  308. other: The other function to chain.
  309. Returns:
  310. The chained function.
  311. """
  312. self_arg_type, self_return_type = unwrap_reflex_callalbe(self._var_type)
  313. _, other_return_type = unwrap_reflex_callalbe(other._var_type)
  314. return ArgsFunctionOperationBuilder.create(
  315. (),
  316. VarOperationCall.create(
  317. other,
  318. VarOperationCall.create(
  319. self, Var(_js_expr="...args"), _var_type=self_return_type
  320. ),
  321. _var_type=other_return_type,
  322. ),
  323. rest="arg",
  324. _var_type=ReflexCallable[self_arg_type, other_return_type], # pyright: ignore [reportInvalidTypeArguments]
  325. )
  326. def _partial_type(
  327. self, *args: Var | Any
  328. ) -> Tuple[GenericType, Optional[TypeComputer]]:
  329. """Override the type of the function call with the given arguments.
  330. Args:
  331. *args: The arguments to call the function with.
  332. Returns:
  333. The overridden type of the function call.
  334. """
  335. args_types, return_type = unwrap_reflex_callalbe(self._var_type)
  336. if isinstance(args_types, tuple):
  337. return ReflexCallable[[*args_types[len(args) :]], return_type], None # type: ignore
  338. return ReflexCallable[..., return_type], None
  339. def _arg_len(self) -> int | None:
  340. """Get the number of arguments the function takes.
  341. Returns:
  342. The number of arguments the function takes.
  343. """
  344. args_types, _ = unwrap_reflex_callalbe(self._var_type)
  345. if isinstance(args_types, tuple):
  346. return len(args_types)
  347. return None
  348. def _required_arg_len(self) -> int:
  349. """Get the number of required arguments the function takes.
  350. Returns:
  351. The number of required arguments the function takes.
  352. """
  353. args_types, _ = unwrap_reflex_callalbe(self._var_type)
  354. if isinstance(args_types, tuple):
  355. return sum(
  356. 1
  357. for arg_type in args_types
  358. if get_origin(arg_type) is not VarWithDefault
  359. )
  360. return 0
  361. def _return_type(self, *args: Var | Any) -> GenericType:
  362. """Override the type of the function call with the given arguments.
  363. Args:
  364. *args: The arguments to call the function with.
  365. Returns:
  366. The overridden type of the function call.
  367. """
  368. partial_types, _ = self._partial_type(*args)
  369. return unwrap_reflex_callalbe(partial_types)[1]
  370. def _pre_check(
  371. self, *args: Var | Any
  372. ) -> Tuple[Callable[[Any], Optional[str]], ...]:
  373. """Check if the function can be called with the given arguments.
  374. Args:
  375. *args: The arguments to call the function with.
  376. Returns:
  377. True if the function can be called with the given arguments.
  378. """
  379. return ()
  380. @overload
  381. def __get__(self, instance: None, owner: Any) -> FunctionVar[CALLABLE_TYPE]: ...
  382. @overload
  383. def __get__(
  384. self: FunctionVar[ReflexCallable[Concatenate[V1, P], R]],
  385. instance: Var[V1],
  386. owner: Any,
  387. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  388. def __get__(self, instance: Any, owner: Any):
  389. """Get the function var.
  390. Args:
  391. instance: The instance of the class.
  392. owner: The owner of the class.
  393. Returns:
  394. The function var.
  395. """
  396. if instance is None:
  397. return self
  398. return self.partial(instance)
  399. __call__ = call
  400. class BuilderFunctionVar(
  401. FunctionVar[CALLABLE_TYPE], default_type=ReflexCallable[Any, Any]
  402. ):
  403. """Base class for immutable function vars with the builder pattern."""
  404. __call__ = FunctionVar.partial
  405. class FunctionStringVar(FunctionVar[CALLABLE_TYPE]):
  406. """Base class for immutable function vars from a string."""
  407. @classmethod
  408. def create(
  409. cls,
  410. func: str,
  411. _var_type: Type[OTHER_CALLABLE_TYPE] = ReflexCallable[Any, Any],
  412. _var_data: VarData | None = None,
  413. ) -> FunctionStringVar[OTHER_CALLABLE_TYPE]:
  414. """Create a new function var from a string.
  415. Args:
  416. func: The function to call.
  417. _var_data: Additional hooks and imports associated with the Var.
  418. Returns:
  419. The function var.
  420. """
  421. return FunctionStringVar(
  422. _js_expr=func,
  423. _var_type=_var_type,
  424. _var_data=_var_data,
  425. )
  426. @dataclasses.dataclass(
  427. eq=False,
  428. frozen=True,
  429. **{"slots": True} if sys.version_info >= (3, 10) else {},
  430. )
  431. class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]):
  432. """Base class for immutable vars that are the result of a function call."""
  433. _func: Optional[FunctionVar[ReflexCallable[..., R]]] = dataclasses.field(
  434. default=None
  435. )
  436. _args: Tuple[Union[Var, Any], ...] = dataclasses.field(default_factory=tuple)
  437. @cached_property_no_lock
  438. def _cached_var_name(self) -> str:
  439. """The name of the var.
  440. Returns:
  441. The name of the var.
  442. """
  443. return f"({self._func!s}({', '.join([str(LiteralVar.create(arg)) for arg in self._args])}))"
  444. @cached_property_no_lock
  445. def _cached_get_all_var_data(self) -> VarData | None:
  446. """Get all the var data associated with the var.
  447. Returns:
  448. All the var data associated with the var.
  449. """
  450. return VarData.merge(
  451. self._func._get_all_var_data() if self._func is not None else None,
  452. *[LiteralVar.create(arg)._get_all_var_data() for arg in self._args],
  453. self._var_data,
  454. )
  455. @classmethod
  456. def create(
  457. cls,
  458. func: FunctionVar[ReflexCallable[P, R]],
  459. *args: Var | Any,
  460. _var_type: GenericType = Any,
  461. _var_data: VarData | None = None,
  462. ) -> VarOperationCall:
  463. """Create a new function call var.
  464. Args:
  465. func: The function to call.
  466. *args: The arguments to call the function with.
  467. _var_data: Additional hooks and imports associated with the Var.
  468. Returns:
  469. The function call var.
  470. """
  471. function_return_type = (
  472. func._var_type.__args__[1]
  473. if getattr(func._var_type, "__args__", None)
  474. else Any
  475. )
  476. var_type = _var_type if _var_type is not Any else function_return_type
  477. return cls(
  478. _js_expr="",
  479. _var_type=var_type,
  480. _var_data=_var_data,
  481. _func=func,
  482. _args=args,
  483. )
  484. @dataclasses.dataclass(frozen=True)
  485. class DestructuredArg:
  486. """Class for destructured arguments."""
  487. fields: Tuple[str, ...] = ()
  488. rest: Optional[str] = None
  489. def to_javascript(self) -> str:
  490. """Convert the destructured argument to JavaScript.
  491. Returns:
  492. The destructured argument in JavaScript.
  493. """
  494. return format.wrap(
  495. ", ".join(self.fields) + (f", ...{self.rest}" if self.rest else ""),
  496. "{",
  497. "}",
  498. )
  499. @dataclasses.dataclass(
  500. frozen=True,
  501. )
  502. class FunctionArgs:
  503. """Class for function arguments."""
  504. args: Tuple[Union[str, DestructuredArg], ...] = ()
  505. rest: Optional[str] = None
  506. def format_args_function_operation(
  507. self: ArgsFunctionOperation | ArgsFunctionOperationBuilder,
  508. ) -> str:
  509. """Format an args function operation.
  510. Args:
  511. self: The function operation.
  512. Returns:
  513. The formatted args function operation.
  514. """
  515. arg_names_str = ", ".join(
  516. [
  517. (arg if isinstance(arg, str) else arg.to_javascript())
  518. + (
  519. f" = {default_value.default!s}"
  520. if i < len(self._default_values)
  521. and not isinstance(
  522. (default_value := self._default_values[i]), inspect.Parameter.empty
  523. )
  524. else ""
  525. )
  526. for i, arg in enumerate(self._args.args)
  527. ]
  528. + ([f"...{self._args.rest}"] if self._args.rest else [])
  529. )
  530. return_expr_str = str(LiteralVar.create(self._return_expr))
  531. # Wrap return expression in curly braces if explicit return syntax is used.
  532. return_expr_str_wrapped = (
  533. format.wrap(return_expr_str, "{", "}")
  534. if self._explicit_return
  535. else return_expr_str
  536. )
  537. return f"(({arg_names_str}) => {return_expr_str_wrapped})"
  538. def pre_check_args(
  539. self: ArgsFunctionOperation | ArgsFunctionOperationBuilder, *args: Var | Any
  540. ) -> Tuple[Callable[[Any], Optional[str]], ...]:
  541. """Check if the function can be called with the given arguments.
  542. Args:
  543. self: The function operation.
  544. *args: The arguments to call the function with.
  545. Returns:
  546. True if the function can be called with the given arguments.
  547. Raises:
  548. VarTypeError: If the arguments are invalid.
  549. """
  550. for i, (validator, arg) in enumerate(zip(self._validators, args)):
  551. if (validation_message := validator(arg)) is not None:
  552. arg_name = self._args.args[i] if i < len(self._args.args) else None
  553. if arg_name is not None:
  554. raise VarTypeError(
  555. f"Invalid argument {arg!s} provided to {arg_name} in {self._function_name or 'var operation'}. {validation_message}"
  556. )
  557. raise VarTypeError(
  558. f"Invalid argument {arg!s} provided to argument {i} in {self._function_name or 'var operation'}. {validation_message}"
  559. )
  560. return self._validators[len(args) :]
  561. def figure_partial_type(
  562. self: ArgsFunctionOperation | ArgsFunctionOperationBuilder,
  563. *args: Var | Any,
  564. ) -> Tuple[GenericType, Optional[TypeComputer]]:
  565. """Figure out the return type of the function.
  566. Args:
  567. self: The function operation.
  568. *args: The arguments to call the function with.
  569. Returns:
  570. The return type of the function.
  571. """
  572. return (
  573. self._type_computer(*args)
  574. if self._type_computer is not None
  575. else FunctionVar._partial_type(self, *args)
  576. )
  577. @dataclasses.dataclass(
  578. eq=False,
  579. frozen=True,
  580. **{"slots": True} if sys.version_info >= (3, 10) else {},
  581. )
  582. class ArgsFunctionOperation(CachedVarOperation, FunctionVar[CALLABLE_TYPE]):
  583. """Base class for immutable function defined via arguments and return expression."""
  584. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  585. _default_values: Tuple[VarWithDefault | inspect.Parameter.empty, ...] = (
  586. dataclasses.field(default_factory=tuple)
  587. )
  588. _validators: Tuple[Callable[[Any], Optional[str]], ...] = dataclasses.field(
  589. default_factory=tuple
  590. )
  591. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  592. _function_name: str = dataclasses.field(default="")
  593. _type_computer: Optional[TypeComputer] = dataclasses.field(default=None)
  594. _explicit_return: bool = dataclasses.field(default=False)
  595. _raw_js_function: str | None = dataclasses.field(default=None)
  596. _cached_var_name = cached_property_no_lock(format_args_function_operation)
  597. _pre_check = pre_check_args # type: ignore
  598. _partial_type = figure_partial_type # type: ignore
  599. @classmethod
  600. def create(
  601. cls,
  602. args_names: Sequence[Union[str, DestructuredArg]],
  603. return_expr: Var | Any,
  604. /,
  605. default_values: Sequence[VarWithDefault | inspect.Parameter.empty] = (),
  606. rest: str | None = None,
  607. validators: Sequence[Callable[[Any], Optional[str]]] = (),
  608. function_name: str = "",
  609. explicit_return: bool = False,
  610. type_computer: Optional[TypeComputer] = None,
  611. _raw_js_function: str | None = None,
  612. _var_type: GenericType = Callable,
  613. _var_data: VarData | None = None,
  614. ):
  615. """Create a new function var.
  616. Args:
  617. args_names: The names of the arguments.
  618. return_expr: The return expression of the function.
  619. default_values: The default values of the arguments.
  620. rest: The name of the rest argument.
  621. validators: The validators for the arguments.
  622. function_name: The name of the function.
  623. explicit_return: Whether to use explicit return syntax.
  624. type_computer: A function to compute the return type.
  625. _raw_js_function: If provided, it will be used when the operation is being called with all of its arguments at once.
  626. _var_type: The type of the var.
  627. _var_data: Additional hooks and imports associated with the Var.
  628. Returns:
  629. The function var.
  630. """
  631. return_expr = Var.create(return_expr)
  632. return cls(
  633. _js_expr="",
  634. _var_type=_var_type,
  635. _var_data=_var_data,
  636. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  637. _raw_js_function=_raw_js_function,
  638. _default_values=tuple(default_values),
  639. _function_name=function_name,
  640. _validators=tuple(validators),
  641. _return_expr=return_expr,
  642. _explicit_return=explicit_return,
  643. _type_computer=type_computer,
  644. )
  645. @dataclasses.dataclass(
  646. eq=False,
  647. frozen=True,
  648. **{"slots": True} if sys.version_info >= (3, 10) else {},
  649. )
  650. class ArgsFunctionOperationBuilder(
  651. CachedVarOperation, BuilderFunctionVar[CALLABLE_TYPE]
  652. ):
  653. """Base class for immutable function defined via arguments and return expression with the builder pattern."""
  654. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  655. _default_values: Tuple[VarWithDefault | inspect.Parameter.empty, ...] = (
  656. dataclasses.field(default_factory=tuple)
  657. )
  658. _validators: Tuple[Callable[[Any], Optional[str]], ...] = dataclasses.field(
  659. default_factory=tuple
  660. )
  661. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  662. _function_name: str = dataclasses.field(default="")
  663. _type_computer: Optional[TypeComputer] = dataclasses.field(default=None)
  664. _explicit_return: bool = dataclasses.field(default=False)
  665. _raw_js_function: str | None = dataclasses.field(default=None)
  666. _cached_var_name = cached_property_no_lock(format_args_function_operation)
  667. _pre_check = pre_check_args # type: ignore
  668. _partial_type = figure_partial_type # type: ignore
  669. @classmethod
  670. def create(
  671. cls,
  672. args_names: Sequence[Union[str, DestructuredArg]],
  673. return_expr: Var | Any,
  674. /,
  675. default_values: Sequence[VarWithDefault | inspect.Parameter.empty] = (),
  676. rest: str | None = None,
  677. validators: Sequence[Callable[[Any], Optional[str]]] = (),
  678. function_name: str = "",
  679. explicit_return: bool = False,
  680. type_computer: Optional[TypeComputer] = None,
  681. _raw_js_function: str | None = None,
  682. _var_type: GenericType = Callable,
  683. _var_data: VarData | None = None,
  684. ):
  685. """Create a new function var.
  686. Args:
  687. args_names: The names of the arguments.
  688. return_expr: The return expression of the function.
  689. default_values: The default values of the arguments.
  690. rest: The name of the rest argument.
  691. validators: The validators for the arguments.
  692. function_name: The name of the function.
  693. explicit_return: Whether to use explicit return syntax.
  694. type_computer: A function to compute the return type.
  695. _var_type: The type of the var.
  696. _var_data: Additional hooks and imports associated with the Var.
  697. _raw_js_function: If provided, it will be used when the operation is being called with all of its arguments at once.
  698. Returns:
  699. The function var.
  700. """
  701. return_expr = Var.create(return_expr)
  702. return cls(
  703. _js_expr="",
  704. _var_type=_var_type,
  705. _var_data=_var_data,
  706. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  707. _raw_js_function=_raw_js_function,
  708. _default_values=tuple(default_values),
  709. _function_name=function_name,
  710. _validators=tuple(validators),
  711. _return_expr=return_expr,
  712. _explicit_return=explicit_return,
  713. _type_computer=type_computer,
  714. )
  715. if python_version := sys.version_info[:2] >= (3, 10):
  716. JSON_STRINGIFY = FunctionStringVar.create(
  717. "JSON.stringify", _var_type=ReflexCallable[[Any], str]
  718. )
  719. ARRAY_ISARRAY = FunctionStringVar.create(
  720. "Array.isArray", _var_type=ReflexCallable[[Any], bool]
  721. )
  722. PROTOTYPE_TO_STRING = FunctionStringVar.create(
  723. "((__to_string) => __to_string.toString())",
  724. _var_type=ReflexCallable[[Any], str],
  725. )
  726. else:
  727. JSON_STRINGIFY = FunctionStringVar.create(
  728. "JSON.stringify", _var_type=ReflexCallable[Any, str]
  729. )
  730. ARRAY_ISARRAY = FunctionStringVar.create(
  731. "Array.isArray", _var_type=ReflexCallable[Any, bool]
  732. )
  733. PROTOTYPE_TO_STRING = FunctionStringVar.create(
  734. "((__to_string) => __to_string.toString())",
  735. _var_type=ReflexCallable[Any, str],
  736. )