function.py 26 KB

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