function.py 14 KB

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