function.py 14 KB

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