object.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. """Classes for immutable object vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import sys
  5. import typing
  6. from inspect import isclass
  7. from typing import (
  8. Any,
  9. List,
  10. Mapping,
  11. NoReturn,
  12. Tuple,
  13. Type,
  14. TypeVar,
  15. Union,
  16. get_args,
  17. overload,
  18. )
  19. from typing_extensions import is_typeddict
  20. from reflex.utils import types
  21. from reflex.utils.exceptions import VarAttributeError
  22. from reflex.utils.types import GenericType, get_attribute_access_type, get_origin
  23. from .base import (
  24. CachedVarOperation,
  25. LiteralVar,
  26. Var,
  27. VarData,
  28. cached_property_no_lock,
  29. figure_out_type,
  30. var_operation,
  31. var_operation_return,
  32. )
  33. from .number import BooleanVar, NumberVar, raise_unsupported_operand_types
  34. from .sequence import ArrayVar, StringVar
  35. OBJECT_TYPE = TypeVar("OBJECT_TYPE", covariant=True)
  36. KEY_TYPE = TypeVar("KEY_TYPE")
  37. VALUE_TYPE = TypeVar("VALUE_TYPE")
  38. ARRAY_INNER_TYPE = TypeVar("ARRAY_INNER_TYPE")
  39. OTHER_KEY_TYPE = TypeVar("OTHER_KEY_TYPE")
  40. class ObjectVar(Var[OBJECT_TYPE], python_types=Mapping):
  41. """Base class for immutable object vars."""
  42. def _key_type(self) -> Type:
  43. """Get the type of the keys of the object.
  44. Returns:
  45. The type of the keys of the object.
  46. """
  47. return str
  48. @overload
  49. def _value_type(
  50. self: ObjectVar[Mapping[Any, VALUE_TYPE]],
  51. ) -> Type[VALUE_TYPE]: ...
  52. @overload
  53. def _value_type(self) -> Type: ...
  54. def _value_type(self) -> Type:
  55. """Get the type of the values of the object.
  56. Returns:
  57. The type of the values of the object.
  58. """
  59. fixed_type = get_origin(self._var_type) or self._var_type
  60. if not isclass(fixed_type):
  61. return Any # pyright: ignore [reportReturnType]
  62. args = get_args(self._var_type) if issubclass(fixed_type, Mapping) else ()
  63. return args[1] if args else Any # pyright: ignore [reportReturnType]
  64. def keys(self) -> ArrayVar[List[str]]:
  65. """Get the keys of the object.
  66. Returns:
  67. The keys of the object.
  68. """
  69. return object_keys_operation(self)
  70. @overload
  71. def values(
  72. self: ObjectVar[Mapping[Any, VALUE_TYPE]],
  73. ) -> ArrayVar[List[VALUE_TYPE]]: ...
  74. @overload
  75. def values(self) -> ArrayVar: ...
  76. def values(self) -> ArrayVar:
  77. """Get the values of the object.
  78. Returns:
  79. The values of the object.
  80. """
  81. return object_values_operation(self)
  82. @overload
  83. def entries(
  84. self: ObjectVar[Mapping[Any, VALUE_TYPE]],
  85. ) -> ArrayVar[List[Tuple[str, VALUE_TYPE]]]: ...
  86. @overload
  87. def entries(self) -> ArrayVar: ...
  88. def entries(self) -> ArrayVar:
  89. """Get the entries of the object.
  90. Returns:
  91. The entries of the object.
  92. """
  93. return object_entries_operation(self)
  94. items = entries
  95. def merge(self, other: ObjectVar):
  96. """Merge two objects.
  97. Args:
  98. other: The other object to merge.
  99. Returns:
  100. The merged object.
  101. """
  102. return object_merge_operation(self, other)
  103. # NoReturn is used here to catch when key value is Any
  104. @overload
  105. def __getitem__( # pyright: ignore [reportOverlappingOverload]
  106. self: ObjectVar[Mapping[Any, NoReturn]],
  107. key: Var | Any,
  108. ) -> Var: ...
  109. @overload
  110. def __getitem__(
  111. self: (ObjectVar[Mapping[Any, bool]]),
  112. key: Var | Any,
  113. ) -> BooleanVar: ...
  114. @overload
  115. def __getitem__(
  116. self: (
  117. ObjectVar[Mapping[Any, int]]
  118. | ObjectVar[Mapping[Any, float]]
  119. | ObjectVar[Mapping[Any, int | float]]
  120. ),
  121. key: Var | Any,
  122. ) -> NumberVar: ...
  123. @overload
  124. def __getitem__(
  125. self: ObjectVar[Mapping[Any, str]],
  126. key: Var | Any,
  127. ) -> StringVar: ...
  128. @overload
  129. def __getitem__(
  130. self: ObjectVar[Mapping[Any, list[ARRAY_INNER_TYPE]]],
  131. key: Var | Any,
  132. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  133. @overload
  134. def __getitem__(
  135. self: ObjectVar[Mapping[Any, set[ARRAY_INNER_TYPE]]],
  136. key: Var | Any,
  137. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  138. @overload
  139. def __getitem__(
  140. self: ObjectVar[Mapping[Any, tuple[ARRAY_INNER_TYPE, ...]]],
  141. key: Var | Any,
  142. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  143. @overload
  144. def __getitem__(
  145. self: ObjectVar[Mapping[Any, Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]],
  146. key: Var | Any,
  147. ) -> ObjectVar[Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
  148. def __getitem__(self, key: Var | Any) -> Var:
  149. """Get an item from the object.
  150. Args:
  151. key: The key to get from the object.
  152. Returns:
  153. The item from the object.
  154. """
  155. if not isinstance(key, (StringVar, str, int, NumberVar)) or (
  156. isinstance(key, NumberVar) and key._is_strict_float()
  157. ):
  158. raise_unsupported_operand_types("[]", (type(self), type(key)))
  159. return ObjectItemOperation.create(self, key).guess_type()
  160. # NoReturn is used here to catch when key value is Any
  161. @overload
  162. def __getattr__( # pyright: ignore [reportOverlappingOverload]
  163. self: ObjectVar[Mapping[Any, NoReturn]],
  164. name: str,
  165. ) -> Var: ...
  166. @overload
  167. def __getattr__(
  168. self: (
  169. ObjectVar[Mapping[Any, int]]
  170. | ObjectVar[Mapping[Any, float]]
  171. | ObjectVar[Mapping[Any, int | float]]
  172. ),
  173. name: str,
  174. ) -> NumberVar: ...
  175. @overload
  176. def __getattr__(
  177. self: ObjectVar[Mapping[Any, str]],
  178. name: str,
  179. ) -> StringVar: ...
  180. @overload
  181. def __getattr__(
  182. self: ObjectVar[Mapping[Any, list[ARRAY_INNER_TYPE]]],
  183. name: str,
  184. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  185. @overload
  186. def __getattr__(
  187. self: ObjectVar[Mapping[Any, set[ARRAY_INNER_TYPE]]],
  188. name: str,
  189. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  190. @overload
  191. def __getattr__(
  192. self: ObjectVar[Mapping[Any, tuple[ARRAY_INNER_TYPE, ...]]],
  193. name: str,
  194. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  195. @overload
  196. def __getattr__(
  197. self: ObjectVar[Mapping[Any, Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]],
  198. name: str,
  199. ) -> ObjectVar[Mapping[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
  200. @overload
  201. def __getattr__(
  202. self: ObjectVar,
  203. name: str,
  204. ) -> ObjectItemOperation: ...
  205. def __getattr__(self, name: str) -> Var:
  206. """Get an attribute of the var.
  207. Args:
  208. name: The name of the attribute.
  209. Raises:
  210. VarAttributeError: The State var has no such attribute or may have been annotated wrongly.
  211. Returns:
  212. The attribute of the var.
  213. """
  214. if name.startswith("__") and name.endswith("__"):
  215. return getattr(super(type(self), self), name)
  216. var_type = self._var_type
  217. if types.is_optional(var_type):
  218. var_type = get_args(var_type)[0]
  219. fixed_type = var_type if isclass(var_type) else get_origin(var_type)
  220. if (
  221. (isclass(fixed_type) and not issubclass(fixed_type, Mapping))
  222. or (fixed_type in types.UnionTypes)
  223. or is_typeddict(fixed_type)
  224. ):
  225. attribute_type = get_attribute_access_type(var_type, name)
  226. if attribute_type is None:
  227. raise VarAttributeError(
  228. f"The State var `{self!s}` has no attribute '{name}' or may have been annotated "
  229. f"wrongly."
  230. )
  231. return ObjectItemOperation.create(self, name, attribute_type).guess_type()
  232. else:
  233. return ObjectItemOperation.create(self, name).guess_type()
  234. def contains(self, key: Var | Any) -> BooleanVar:
  235. """Check if the object contains a key.
  236. Args:
  237. key: The key to check.
  238. Returns:
  239. The result of the check.
  240. """
  241. return object_has_own_property_operation(self, key)
  242. @dataclasses.dataclass(
  243. eq=False,
  244. frozen=True,
  245. **{"slots": True} if sys.version_info >= (3, 10) else {},
  246. )
  247. class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar):
  248. """Base class for immutable literal object vars."""
  249. _var_value: Mapping[Union[Var, Any], Union[Var, Any]] = dataclasses.field(
  250. default_factory=dict
  251. )
  252. def _key_type(self) -> Type:
  253. """Get the type of the keys of the object.
  254. Returns:
  255. The type of the keys of the object.
  256. """
  257. args_list = typing.get_args(self._var_type)
  258. return args_list[0] if args_list else Any # pyright: ignore [reportReturnType]
  259. def _value_type(self) -> Type:
  260. """Get the type of the values of the object.
  261. Returns:
  262. The type of the values of the object.
  263. """
  264. args_list = typing.get_args(self._var_type)
  265. return args_list[1] if args_list else Any # pyright: ignore [reportReturnType]
  266. @cached_property_no_lock
  267. def _cached_var_name(self) -> str:
  268. """The name of the var.
  269. Returns:
  270. The name of the var.
  271. """
  272. return (
  273. "({ "
  274. + ", ".join(
  275. [
  276. f"[{LiteralVar.create(key)!s}] : {LiteralVar.create(value)!s}"
  277. for key, value in self._var_value.items()
  278. ]
  279. )
  280. + " })"
  281. )
  282. def json(self) -> str:
  283. """Get the JSON representation of the object.
  284. Returns:
  285. The JSON representation of the object.
  286. """
  287. return (
  288. "{"
  289. + ", ".join(
  290. [
  291. f"{LiteralVar.create(key).json()}:{LiteralVar.create(value).json()}"
  292. for key, value in self._var_value.items()
  293. ]
  294. )
  295. + "}"
  296. )
  297. def __hash__(self) -> int:
  298. """Get the hash of the var.
  299. Returns:
  300. The hash of the var.
  301. """
  302. return hash((type(self).__name__, self._js_expr))
  303. @cached_property_no_lock
  304. def _cached_get_all_var_data(self) -> VarData | None:
  305. """Get all the var data.
  306. Returns:
  307. The var data.
  308. """
  309. return VarData.merge(
  310. *[LiteralVar.create(var)._get_all_var_data() for var in self._var_value],
  311. *[
  312. LiteralVar.create(var)._get_all_var_data()
  313. for var in self._var_value.values()
  314. ],
  315. self._var_data,
  316. )
  317. @classmethod
  318. def create(
  319. cls,
  320. _var_value: Mapping,
  321. _var_type: Type[OBJECT_TYPE] | None = None,
  322. _var_data: VarData | None = None,
  323. ) -> LiteralObjectVar[OBJECT_TYPE]:
  324. """Create the literal object var.
  325. Args:
  326. _var_value: The value of the var.
  327. _var_type: The type of the var.
  328. _var_data: Additional hooks and imports associated with the Var.
  329. Returns:
  330. The literal object var.
  331. """
  332. return LiteralObjectVar(
  333. _js_expr="",
  334. _var_type=(figure_out_type(_var_value) if _var_type is None else _var_type),
  335. _var_data=_var_data,
  336. _var_value=_var_value,
  337. )
  338. @var_operation
  339. def object_keys_operation(value: ObjectVar):
  340. """Get the keys of an object.
  341. Args:
  342. value: The object to get the keys from.
  343. Returns:
  344. The keys of the object.
  345. """
  346. return var_operation_return(
  347. js_expression=f"Object.keys({value})",
  348. var_type=List[str],
  349. )
  350. @var_operation
  351. def object_values_operation(value: ObjectVar):
  352. """Get the values of an object.
  353. Args:
  354. value: The object to get the values from.
  355. Returns:
  356. The values of the object.
  357. """
  358. return var_operation_return(
  359. js_expression=f"Object.values({value})",
  360. var_type=List[value._value_type()],
  361. )
  362. @var_operation
  363. def object_entries_operation(value: ObjectVar):
  364. """Get the entries of an object.
  365. Args:
  366. value: The object to get the entries from.
  367. Returns:
  368. The entries of the object.
  369. """
  370. return var_operation_return(
  371. js_expression=f"Object.entries({value})",
  372. var_type=List[Tuple[str, value._value_type()]],
  373. )
  374. @var_operation
  375. def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar):
  376. """Merge two objects.
  377. Args:
  378. lhs: The first object to merge.
  379. rhs: The second object to merge.
  380. Returns:
  381. The merged object.
  382. """
  383. return var_operation_return(
  384. js_expression=f"({{...{lhs}, ...{rhs}}})",
  385. var_type=Mapping[
  386. Union[lhs._key_type(), rhs._key_type()],
  387. Union[lhs._value_type(), rhs._value_type()],
  388. ],
  389. )
  390. @dataclasses.dataclass(
  391. eq=False,
  392. frozen=True,
  393. **{"slots": True} if sys.version_info >= (3, 10) else {},
  394. )
  395. class ObjectItemOperation(CachedVarOperation, Var):
  396. """Operation to get an item from an object."""
  397. _object: ObjectVar = dataclasses.field(
  398. default_factory=lambda: LiteralObjectVar.create({})
  399. )
  400. _key: Var | Any = dataclasses.field(default_factory=lambda: LiteralVar.create(None))
  401. @cached_property_no_lock
  402. def _cached_var_name(self) -> str:
  403. """The name of the operation.
  404. Returns:
  405. The name of the operation.
  406. """
  407. if types.is_optional(self._object._var_type):
  408. return f"{self._object!s}?.[{self._key!s}]"
  409. return f"{self._object!s}[{self._key!s}]"
  410. @classmethod
  411. def create(
  412. cls,
  413. object: ObjectVar,
  414. key: Var | Any,
  415. _var_type: GenericType | None = None,
  416. _var_data: VarData | None = None,
  417. ) -> ObjectItemOperation:
  418. """Create the object item operation.
  419. Args:
  420. object: The object to get the item from.
  421. key: The key to get from the object.
  422. _var_type: The type of the item.
  423. _var_data: Additional hooks and imports associated with the operation.
  424. Returns:
  425. The object item operation.
  426. """
  427. return cls(
  428. _js_expr="",
  429. _var_type=object._value_type() if _var_type is None else _var_type,
  430. _var_data=_var_data,
  431. _object=object,
  432. _key=key if isinstance(key, Var) else LiteralVar.create(key),
  433. )
  434. @var_operation
  435. def object_has_own_property_operation(object: ObjectVar, key: Var):
  436. """Check if an object has a key.
  437. Args:
  438. object: The object to check.
  439. key: The key to check.
  440. Returns:
  441. The result of the check.
  442. """
  443. return var_operation_return(
  444. js_expression=f"{object}.hasOwnProperty({key})",
  445. var_type=bool,
  446. )