function.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. """Immutable function vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import sys
  5. from typing import Any, Generic, Optional, Sequence, Tuple, Type, Union, overload
  6. from typing_extensions import Callable, Concatenate, ParamSpec, Protocol, TypeVar
  7. from reflex.utils import format
  8. from reflex.utils.types import GenericType
  9. from .base import CachedVarOperation, LiteralVar, Var, VarData, cached_property_no_lock
  10. P = ParamSpec("P")
  11. V1 = TypeVar("V1")
  12. V2 = TypeVar("V2")
  13. V3 = TypeVar("V3")
  14. V4 = TypeVar("V4")
  15. V5 = TypeVar("V5")
  16. V6 = TypeVar("V6")
  17. R = TypeVar("R")
  18. class ReflexCallable(Protocol[P, R]):
  19. """Protocol for a callable."""
  20. __call__: Callable[P, R]
  21. CALLABLE_TYPE = TypeVar("CALLABLE_TYPE", bound=ReflexCallable, infer_variance=True)
  22. OTHER_CALLABLE_TYPE = TypeVar(
  23. "OTHER_CALLABLE_TYPE", bound=ReflexCallable, infer_variance=True
  24. )
  25. class FunctionVar(Var[CALLABLE_TYPE], default_type=ReflexCallable[..., Any]):
  26. """Base class for immutable function vars."""
  27. @overload
  28. def partial(self) -> FunctionVar[CALLABLE_TYPE]: ...
  29. @overload
  30. def partial(
  31. self: FunctionVar[ReflexCallable[Concatenate[V1, P], R]],
  32. arg1: Union[V1, Var[V1]],
  33. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  34. @overload
  35. def partial(
  36. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, P], R]],
  37. arg1: Union[V1, Var[V1]],
  38. arg2: Union[V2, Var[V2]],
  39. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  40. @overload
  41. def partial(
  42. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, P], R]],
  43. arg1: Union[V1, Var[V1]],
  44. arg2: Union[V2, Var[V2]],
  45. arg3: Union[V3, Var[V3]],
  46. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  47. @overload
  48. def partial(
  49. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, P], R]],
  50. arg1: Union[V1, Var[V1]],
  51. arg2: Union[V2, Var[V2]],
  52. arg3: Union[V3, Var[V3]],
  53. arg4: Union[V4, Var[V4]],
  54. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  55. @overload
  56. def partial(
  57. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, V5, P], R]],
  58. arg1: Union[V1, Var[V1]],
  59. arg2: Union[V2, Var[V2]],
  60. arg3: Union[V3, Var[V3]],
  61. arg4: Union[V4, Var[V4]],
  62. arg5: Union[V5, Var[V5]],
  63. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  64. @overload
  65. def partial(
  66. self: FunctionVar[ReflexCallable[Concatenate[V1, V2, V3, V4, V5, V6, P], R]],
  67. arg1: Union[V1, Var[V1]],
  68. arg2: Union[V2, Var[V2]],
  69. arg3: Union[V3, Var[V3]],
  70. arg4: Union[V4, Var[V4]],
  71. arg5: Union[V5, Var[V5]],
  72. arg6: Union[V6, Var[V6]],
  73. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  74. @overload
  75. def partial(
  76. self: FunctionVar[ReflexCallable[..., R]], *args: Var | Any
  77. ) -> FunctionVar[ReflexCallable[..., R]]: ...
  78. @overload
  79. def partial(self, *args: Var | Any) -> FunctionVar: ...
  80. def partial(self, *args: Var | Any) -> FunctionVar: # type: ignore
  81. """Partially apply the function with the given arguments.
  82. Args:
  83. *args: The arguments to partially apply the function with.
  84. Returns:
  85. The partially applied function.
  86. """
  87. if not args:
  88. return ArgsFunctionOperation.create((), self)
  89. return ArgsFunctionOperation.create(
  90. ("...args",),
  91. VarOperationCall.create(self, *args, Var(_js_expr="...args")),
  92. )
  93. @overload
  94. def call(
  95. self: FunctionVar[ReflexCallable[[V1], R]], arg1: Union[V1, Var[V1]]
  96. ) -> VarOperationCall[[V1], R]: ...
  97. @overload
  98. def call(
  99. self: FunctionVar[ReflexCallable[[V1, V2], R]],
  100. arg1: Union[V1, Var[V1]],
  101. arg2: Union[V2, Var[V2]],
  102. ) -> VarOperationCall[[V1, V2], R]: ...
  103. @overload
  104. def call(
  105. self: FunctionVar[ReflexCallable[[V1, V2, V3], R]],
  106. arg1: Union[V1, Var[V1]],
  107. arg2: Union[V2, Var[V2]],
  108. arg3: Union[V3, Var[V3]],
  109. ) -> VarOperationCall[[V1, V2, V3], R]: ...
  110. @overload
  111. def call(
  112. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4], R]],
  113. arg1: Union[V1, Var[V1]],
  114. arg2: Union[V2, Var[V2]],
  115. arg3: Union[V3, Var[V3]],
  116. arg4: Union[V4, Var[V4]],
  117. ) -> VarOperationCall[[V1, V2, V3, V4], R]: ...
  118. @overload
  119. def call(
  120. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4, V5], R]],
  121. arg1: Union[V1, Var[V1]],
  122. arg2: Union[V2, Var[V2]],
  123. arg3: Union[V3, Var[V3]],
  124. arg4: Union[V4, Var[V4]],
  125. arg5: Union[V5, Var[V5]],
  126. ) -> VarOperationCall[[V1, V2, V3, V4, V5], R]: ...
  127. @overload
  128. def call(
  129. self: FunctionVar[ReflexCallable[[V1, V2, V3, V4, V5, V6], R]],
  130. arg1: Union[V1, Var[V1]],
  131. arg2: Union[V2, Var[V2]],
  132. arg3: Union[V3, Var[V3]],
  133. arg4: Union[V4, Var[V4]],
  134. arg5: Union[V5, Var[V5]],
  135. arg6: Union[V6, Var[V6]],
  136. ) -> VarOperationCall[[V1, V2, V3, V4, V5, V6], R]: ...
  137. @overload
  138. def call(
  139. self: FunctionVar[ReflexCallable[..., R]], *args: Var | Any
  140. ) -> VarOperationCall[..., R]: ...
  141. def call(self, *args: Var | Any) -> Var: # type: ignore
  142. """Call the function with the given arguments.
  143. Args:
  144. *args: The arguments to call the function with.
  145. Returns:
  146. The function call operation.
  147. """
  148. return VarOperationCall.create(self, *args).guess_type()
  149. __call__ = call
  150. class BuilderFunctionVar(
  151. FunctionVar[CALLABLE_TYPE], default_type=ReflexCallable[..., Any]
  152. ):
  153. """Base class for immutable function vars with the builder pattern."""
  154. __call__ = FunctionVar.partial
  155. class FunctionStringVar(FunctionVar[CALLABLE_TYPE]):
  156. """Base class for immutable function vars from a string."""
  157. @classmethod
  158. def create(
  159. cls,
  160. func: str,
  161. _var_type: Type[OTHER_CALLABLE_TYPE] = ReflexCallable[..., Any],
  162. _var_data: VarData | None = None,
  163. ) -> FunctionStringVar[OTHER_CALLABLE_TYPE]:
  164. """Create a new function var from a string.
  165. Args:
  166. func: The function to call.
  167. _var_data: Additional hooks and imports associated with the Var.
  168. Returns:
  169. The function var.
  170. """
  171. return FunctionStringVar(
  172. _js_expr=func,
  173. _var_type=_var_type,
  174. _var_data=_var_data,
  175. )
  176. @dataclasses.dataclass(
  177. eq=False,
  178. frozen=True,
  179. **{"slots": True} if sys.version_info >= (3, 10) else {},
  180. )
  181. class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]):
  182. """Base class for immutable vars that are the result of a function call."""
  183. _func: Optional[FunctionVar[ReflexCallable[P, R]]] = dataclasses.field(default=None)
  184. _args: Tuple[Union[Var, Any], ...] = dataclasses.field(default_factory=tuple)
  185. @cached_property_no_lock
  186. def _cached_var_name(self) -> str:
  187. """The name of the var.
  188. Returns:
  189. The name of the var.
  190. """
  191. return f"({str(self._func)}({', '.join([str(LiteralVar.create(arg)) for arg in self._args])}))"
  192. @cached_property_no_lock
  193. def _cached_get_all_var_data(self) -> VarData | None:
  194. """Get all the var data associated with the var.
  195. Returns:
  196. All the var data associated with the var.
  197. """
  198. return VarData.merge(
  199. self._func._get_all_var_data() if self._func is not None else None,
  200. *[LiteralVar.create(arg)._get_all_var_data() for arg in self._args],
  201. self._var_data,
  202. )
  203. @classmethod
  204. def create(
  205. cls,
  206. func: FunctionVar[ReflexCallable[P, R]],
  207. *args: Var | Any,
  208. _var_type: GenericType = Any,
  209. _var_data: VarData | None = None,
  210. ) -> VarOperationCall:
  211. """Create a new function call var.
  212. Args:
  213. func: The function to call.
  214. *args: The arguments to call the function with.
  215. _var_data: Additional hooks and imports associated with the Var.
  216. Returns:
  217. The function call var.
  218. """
  219. function_return_type = (
  220. func._var_type.__args__[1]
  221. if getattr(func._var_type, "__args__", None)
  222. else Any
  223. )
  224. var_type = _var_type if _var_type is not Any else function_return_type
  225. return cls(
  226. _js_expr="",
  227. _var_type=var_type,
  228. _var_data=_var_data,
  229. _func=func,
  230. _args=args,
  231. )
  232. @dataclasses.dataclass(frozen=True)
  233. class DestructuredArg:
  234. """Class for destructured arguments."""
  235. fields: Tuple[str, ...] = tuple()
  236. rest: Optional[str] = None
  237. def to_javascript(self) -> str:
  238. """Convert the destructured argument to JavaScript.
  239. Returns:
  240. The destructured argument in JavaScript.
  241. """
  242. return format.wrap(
  243. ", ".join(self.fields) + (f", ...{self.rest}" if self.rest else ""),
  244. "{",
  245. "}",
  246. )
  247. @dataclasses.dataclass(
  248. frozen=True,
  249. )
  250. class FunctionArgs:
  251. """Class for function arguments."""
  252. args: Tuple[Union[str, DestructuredArg], ...] = tuple()
  253. rest: Optional[str] = None
  254. def format_args_function_operation(
  255. args: FunctionArgs, return_expr: Var | Any, explicit_return: bool
  256. ) -> str:
  257. """Format an args function operation.
  258. Args:
  259. args: The function arguments.
  260. return_expr: The return expression.
  261. explicit_return: Whether to use explicit return syntax.
  262. Returns:
  263. The formatted args function operation.
  264. """
  265. arg_names_str = ", ".join(
  266. [arg if isinstance(arg, str) else arg.to_javascript() for arg in args.args]
  267. ) + (f", ...{args.rest}" if args.rest else "")
  268. return_expr_str = str(LiteralVar.create(return_expr))
  269. # Wrap return expression in curly braces if explicit return syntax is used.
  270. return_expr_str_wrapped = (
  271. format.wrap(return_expr_str, "{", "}") if explicit_return else return_expr_str
  272. )
  273. return f"(({arg_names_str}) => {return_expr_str_wrapped})"
  274. @dataclasses.dataclass(
  275. eq=False,
  276. frozen=True,
  277. **{"slots": True} if sys.version_info >= (3, 10) else {},
  278. )
  279. class ArgsFunctionOperation(CachedVarOperation, FunctionVar):
  280. """Base class for immutable function defined via arguments and return expression."""
  281. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  282. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  283. _explicit_return: bool = dataclasses.field(default=False)
  284. @cached_property_no_lock
  285. def _cached_var_name(self) -> str:
  286. """The name of the var.
  287. Returns:
  288. The name of the var.
  289. """
  290. return format_args_function_operation(
  291. self._args, self._return_expr, self._explicit_return
  292. )
  293. @classmethod
  294. def create(
  295. cls,
  296. args_names: Sequence[Union[str, DestructuredArg]],
  297. return_expr: Var | Any,
  298. rest: str | None = None,
  299. explicit_return: bool = False,
  300. _var_type: GenericType = Callable,
  301. _var_data: VarData | None = None,
  302. ):
  303. """Create a new function var.
  304. Args:
  305. args_names: The names of the arguments.
  306. return_expr: The return expression of the function.
  307. rest: The name of the rest argument.
  308. explicit_return: Whether to use explicit return syntax.
  309. _var_data: Additional hooks and imports associated with the Var.
  310. Returns:
  311. The function var.
  312. """
  313. return cls(
  314. _js_expr="",
  315. _var_type=_var_type,
  316. _var_data=_var_data,
  317. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  318. _return_expr=return_expr,
  319. _explicit_return=explicit_return,
  320. )
  321. @dataclasses.dataclass(
  322. eq=False,
  323. frozen=True,
  324. **{"slots": True} if sys.version_info >= (3, 10) else {},
  325. )
  326. class ArgsFunctionOperationBuilder(CachedVarOperation, BuilderFunctionVar):
  327. """Base class for immutable function defined via arguments and return expression with the builder pattern."""
  328. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  329. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  330. _explicit_return: bool = dataclasses.field(default=False)
  331. @cached_property_no_lock
  332. def _cached_var_name(self) -> str:
  333. """The name of the var.
  334. Returns:
  335. The name of the var.
  336. """
  337. return format_args_function_operation(
  338. self._args, self._return_expr, self._explicit_return
  339. )
  340. @classmethod
  341. def create(
  342. cls,
  343. args_names: Sequence[Union[str, DestructuredArg]],
  344. return_expr: Var | Any,
  345. rest: str | None = None,
  346. explicit_return: bool = False,
  347. _var_type: GenericType = Callable,
  348. _var_data: VarData | None = None,
  349. ):
  350. """Create a new function var.
  351. Args:
  352. args_names: The names of the arguments.
  353. return_expr: The return expression of the function.
  354. rest: The name of the rest argument.
  355. explicit_return: Whether to use explicit return syntax.
  356. _var_data: Additional hooks and imports associated with the Var.
  357. Returns:
  358. The function var.
  359. """
  360. return cls(
  361. _js_expr="",
  362. _var_type=_var_type,
  363. _var_data=_var_data,
  364. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  365. _return_expr=return_expr,
  366. _explicit_return=explicit_return,
  367. )
  368. JSON_STRINGIFY = FunctionStringVar.create(
  369. "JSON.stringify", _var_type=ReflexCallable[[Any], str]
  370. )
  371. ARRAY_ISARRAY = FunctionStringVar.create("Array.isArray")
  372. PROTOTYPE_TO_STRING = FunctionStringVar.create(
  373. "((__to_string) => __to_string.toString())"
  374. )