function.py 26 KB

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