function.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. """Immutable function vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import sys
  5. from typing import Any, Callable, Optional, Sequence, Tuple, Type, Union, overload
  6. from typing_extensions import Concatenate, Generic, 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, 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[P, R]], *args: Var | Any
  77. ) -> FunctionVar[ReflexCallable[P, R]]: ...
  78. @overload
  79. def partial(self, *args: Var | Any) -> FunctionVar: ...
  80. def partial(self, *args: Var | Any) -> FunctionVar: # pyright: ignore [reportInconsistentOverload]
  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[P, R]], *args: Var | Any
  140. ) -> VarOperationCall[P, R]: ...
  141. @overload
  142. def call(self, *args: Var | Any) -> Var: ...
  143. def call(self, *args: Var | Any) -> Var: # pyright: ignore [reportInconsistentOverload]
  144. """Call the function with the given arguments.
  145. Args:
  146. *args: The arguments to call the function with.
  147. Returns:
  148. The function call operation.
  149. """
  150. return VarOperationCall.create(self, *args).guess_type()
  151. __call__ = call
  152. class BuilderFunctionVar(
  153. FunctionVar[CALLABLE_TYPE], default_type=ReflexCallable[Any, Any]
  154. ):
  155. """Base class for immutable function vars with the builder pattern."""
  156. __call__ = FunctionVar.partial
  157. class FunctionStringVar(FunctionVar[CALLABLE_TYPE]):
  158. """Base class for immutable function vars from a string."""
  159. @classmethod
  160. def create(
  161. cls,
  162. func: str,
  163. _var_type: Type[OTHER_CALLABLE_TYPE] = ReflexCallable[Any, Any],
  164. _var_data: VarData | None = None,
  165. ) -> FunctionStringVar[OTHER_CALLABLE_TYPE]:
  166. """Create a new function var from a string.
  167. Args:
  168. func: The function to call.
  169. _var_type: The type of the Var.
  170. _var_data: Additional hooks and imports associated with the Var.
  171. Returns:
  172. The function var.
  173. """
  174. return FunctionStringVar(
  175. _js_expr=func,
  176. _var_type=_var_type,
  177. _var_data=_var_data,
  178. )
  179. @dataclasses.dataclass(
  180. eq=False,
  181. frozen=True,
  182. slots=True,
  183. )
  184. class VarOperationCall(Generic[P, R], CachedVarOperation, Var[R]):
  185. """Base class for immutable vars that are the result of a function call."""
  186. _func: Optional[FunctionVar[ReflexCallable[P, R]]] = dataclasses.field(default=None)
  187. _args: Tuple[Union[Var, Any], ...] = dataclasses.field(default_factory=tuple)
  188. @cached_property_no_lock
  189. def _cached_var_name(self) -> str:
  190. """The name of the var.
  191. Returns:
  192. The name of the var.
  193. """
  194. return f"({self._func!s}({', '.join([str(LiteralVar.create(arg)) for arg in self._args])}))"
  195. @cached_property_no_lock
  196. def _cached_get_all_var_data(self) -> VarData | None:
  197. """Get all the var data associated with the var.
  198. Returns:
  199. All the var data associated with the var.
  200. """
  201. return VarData.merge(
  202. self._func._get_all_var_data() if self._func is not None else None,
  203. *[LiteralVar.create(arg)._get_all_var_data() for arg in self._args],
  204. self._var_data,
  205. )
  206. @classmethod
  207. def create(
  208. cls,
  209. func: FunctionVar[ReflexCallable[P, R]],
  210. *args: Var | Any,
  211. _var_type: GenericType = Any,
  212. _var_data: VarData | None = None,
  213. ) -> VarOperationCall:
  214. """Create a new function call var.
  215. Args:
  216. func: The function to call.
  217. *args: The arguments to call the function with.
  218. _var_type: The type of the Var.
  219. _var_data: Additional hooks and imports associated with the Var.
  220. Returns:
  221. The function call var.
  222. """
  223. function_return_type = (
  224. func._var_type.__args__[1]
  225. if getattr(func._var_type, "__args__", None)
  226. else Any
  227. )
  228. var_type = _var_type if _var_type is not Any else function_return_type
  229. return cls(
  230. _js_expr="",
  231. _var_type=var_type,
  232. _var_data=_var_data,
  233. _func=func,
  234. _args=args,
  235. )
  236. @dataclasses.dataclass(frozen=True)
  237. class DestructuredArg:
  238. """Class for destructured arguments."""
  239. fields: Tuple[str, ...] = ()
  240. rest: Optional[str] = None
  241. def to_javascript(self) -> str:
  242. """Convert the destructured argument to JavaScript.
  243. Returns:
  244. The destructured argument in JavaScript.
  245. """
  246. return format.wrap(
  247. ", ".join(self.fields) + (f", ...{self.rest}" if self.rest else ""),
  248. "{",
  249. "}",
  250. )
  251. @dataclasses.dataclass(
  252. frozen=True,
  253. )
  254. class FunctionArgs:
  255. """Class for function arguments."""
  256. args: Tuple[Union[str, DestructuredArg], ...] = ()
  257. rest: Optional[str] = None
  258. def format_args_function_operation(
  259. args: FunctionArgs, return_expr: Var | Any, explicit_return: bool
  260. ) -> str:
  261. """Format an args function operation.
  262. Args:
  263. args: The function arguments.
  264. return_expr: The return expression.
  265. explicit_return: Whether to use explicit return syntax.
  266. Returns:
  267. The formatted args function operation.
  268. """
  269. arg_names_str = ", ".join(
  270. [arg if isinstance(arg, str) else arg.to_javascript() for arg in args.args]
  271. ) + (f", ...{args.rest}" if args.rest else "")
  272. return_expr_str = str(LiteralVar.create(return_expr))
  273. # Wrap return expression in curly braces if explicit return syntax is used.
  274. return_expr_str_wrapped = (
  275. format.wrap(return_expr_str, "{", "}") if explicit_return else return_expr_str
  276. )
  277. return f"(({arg_names_str}) => {return_expr_str_wrapped})"
  278. @dataclasses.dataclass(
  279. eq=False,
  280. frozen=True,
  281. slots=True,
  282. )
  283. class ArgsFunctionOperation(CachedVarOperation, FunctionVar):
  284. """Base class for immutable function defined via arguments and return expression."""
  285. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  286. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  287. _explicit_return: bool = dataclasses.field(default=False)
  288. @cached_property_no_lock
  289. def _cached_var_name(self) -> str:
  290. """The name of the var.
  291. Returns:
  292. The name of the var.
  293. """
  294. return format_args_function_operation(
  295. self._args, self._return_expr, self._explicit_return
  296. )
  297. @classmethod
  298. def create(
  299. cls,
  300. args_names: Sequence[Union[str, DestructuredArg]],
  301. return_expr: Var | Any,
  302. rest: str | None = None,
  303. explicit_return: bool = False,
  304. _var_type: GenericType = Callable,
  305. _var_data: VarData | None = None,
  306. ):
  307. """Create a new function var.
  308. Args:
  309. args_names: The names of the arguments.
  310. return_expr: The return expression of the function.
  311. rest: The name of the rest argument.
  312. explicit_return: Whether to use explicit return syntax.
  313. _var_type: The type of the Var.
  314. _var_data: Additional hooks and imports associated with the Var.
  315. Returns:
  316. The function var.
  317. """
  318. return_expr = Var.create(return_expr)
  319. return cls(
  320. _js_expr="",
  321. _var_type=_var_type,
  322. _var_data=_var_data,
  323. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  324. _return_expr=return_expr,
  325. _explicit_return=explicit_return,
  326. )
  327. @dataclasses.dataclass(
  328. eq=False,
  329. frozen=True,
  330. slots=True,
  331. )
  332. class ArgsFunctionOperationBuilder(CachedVarOperation, BuilderFunctionVar):
  333. """Base class for immutable function defined via arguments and return expression with the builder pattern."""
  334. _args: FunctionArgs = dataclasses.field(default_factory=FunctionArgs)
  335. _return_expr: Union[Var, Any] = dataclasses.field(default=None)
  336. _explicit_return: bool = dataclasses.field(default=False)
  337. @cached_property_no_lock
  338. def _cached_var_name(self) -> str:
  339. """The name of the var.
  340. Returns:
  341. The name of the var.
  342. """
  343. return format_args_function_operation(
  344. self._args, self._return_expr, self._explicit_return
  345. )
  346. @classmethod
  347. def create(
  348. cls,
  349. args_names: Sequence[Union[str, DestructuredArg]],
  350. return_expr: Var | Any,
  351. rest: str | None = None,
  352. explicit_return: bool = False,
  353. _var_type: GenericType = Callable,
  354. _var_data: VarData | None = None,
  355. ):
  356. """Create a new function var.
  357. Args:
  358. args_names: The names of the arguments.
  359. return_expr: The return expression of the function.
  360. rest: The name of the rest argument.
  361. explicit_return: Whether to use explicit return syntax.
  362. _var_type: The type of the Var.
  363. _var_data: Additional hooks and imports associated with the Var.
  364. Returns:
  365. The function var.
  366. """
  367. return_expr = Var.create(return_expr)
  368. return cls(
  369. _js_expr="",
  370. _var_type=_var_type,
  371. _var_data=_var_data,
  372. _args=FunctionArgs(args=tuple(args_names), rest=rest),
  373. _return_expr=return_expr,
  374. _explicit_return=explicit_return,
  375. )
  376. if python_version := sys.version_info[:2] >= (3, 10):
  377. JSON_STRINGIFY = FunctionStringVar.create(
  378. "JSON.stringify", _var_type=ReflexCallable[[Any], str]
  379. )
  380. ARRAY_ISARRAY = FunctionStringVar.create(
  381. "Array.isArray", _var_type=ReflexCallable[[Any], bool]
  382. )
  383. PROTOTYPE_TO_STRING = FunctionStringVar.create(
  384. "((__to_string) => __to_string.toString())",
  385. _var_type=ReflexCallable[[Any], str],
  386. )
  387. else:
  388. JSON_STRINGIFY = FunctionStringVar.create(
  389. "JSON.stringify", _var_type=ReflexCallable[Any, str]
  390. )
  391. ARRAY_ISARRAY = FunctionStringVar.create(
  392. "Array.isArray", _var_type=ReflexCallable[Any, bool]
  393. )
  394. PROTOTYPE_TO_STRING = FunctionStringVar.create(
  395. "((__to_string) => __to_string.toString())",
  396. _var_type=ReflexCallable[Any, str],
  397. )