object.py 14 KB

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