object.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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")
  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[Any, 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[Any, 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[Any, 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[Any, NoReturn]],
  106. key: Var | Any,
  107. ) -> Var: ...
  108. @overload
  109. def __getitem__(
  110. self: (
  111. ObjectVar[Dict[Any, int]]
  112. | ObjectVar[Dict[Any, float]]
  113. | ObjectVar[Dict[Any, int | float]]
  114. ),
  115. key: Var | Any,
  116. ) -> NumberVar: ...
  117. @overload
  118. def __getitem__(
  119. self: ObjectVar[Dict[Any, str]],
  120. key: Var | Any,
  121. ) -> StringVar: ...
  122. @overload
  123. def __getitem__(
  124. self: ObjectVar[Dict[Any, list[ARRAY_INNER_TYPE]]],
  125. key: Var | Any,
  126. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  127. @overload
  128. def __getitem__(
  129. self: ObjectVar[Dict[Any, set[ARRAY_INNER_TYPE]]],
  130. key: Var | Any,
  131. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  132. @overload
  133. def __getitem__(
  134. self: ObjectVar[Dict[Any, tuple[ARRAY_INNER_TYPE, ...]]],
  135. key: Var | Any,
  136. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  137. @overload
  138. def __getitem__(
  139. self: ObjectVar[Dict[Any, 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[Any, NoReturn]],
  158. name: str,
  159. ) -> Var: ...
  160. @overload
  161. def __getattr__(
  162. self: (
  163. ObjectVar[Dict[Any, int]]
  164. | ObjectVar[Dict[Any, float]]
  165. | ObjectVar[Dict[Any, int | float]]
  166. ),
  167. name: str,
  168. ) -> NumberVar: ...
  169. @overload
  170. def __getattr__(
  171. self: ObjectVar[Dict[Any, str]],
  172. name: str,
  173. ) -> StringVar: ...
  174. @overload
  175. def __getattr__(
  176. self: ObjectVar[Dict[Any, list[ARRAY_INNER_TYPE]]],
  177. name: str,
  178. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  179. @overload
  180. def __getattr__(
  181. self: ObjectVar[Dict[Any, set[ARRAY_INNER_TYPE]]],
  182. name: str,
  183. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  184. @overload
  185. def __getattr__(
  186. self: ObjectVar[Dict[Any, tuple[ARRAY_INNER_TYPE, ...]]],
  187. name: str,
  188. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  189. @overload
  190. def __getattr__(
  191. self: ObjectVar[Dict[Any, dict[OTHER_KEY_TYPE, VALUE_TYPE]]],
  192. name: str,
  193. ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
  194. @overload
  195. def __getattr__(
  196. self: ObjectVar,
  197. name: str,
  198. ) -> ObjectItemOperation: ...
  199. def __getattr__(self, name) -> Var:
  200. """Get an attribute of the var.
  201. Args:
  202. name: The name of the attribute.
  203. Raises:
  204. VarAttributeError: The State var has no such attribute or may have been annotated wrongly.
  205. Returns:
  206. The attribute of the var.
  207. """
  208. if name.startswith("__") and name.endswith("__"):
  209. return getattr(super(type(self), self), name)
  210. var_type = self._var_type
  211. if types.is_optional(var_type):
  212. var_type = get_args(var_type)[0]
  213. fixed_type = var_type if isclass(var_type) else get_origin(var_type)
  214. if (isclass(fixed_type) and not issubclass(fixed_type, dict)) or (
  215. fixed_type in types.UnionTypes
  216. ):
  217. attribute_type = get_attribute_access_type(var_type, name)
  218. if attribute_type is None:
  219. raise VarAttributeError(
  220. f"The State var `{self!s}` has no attribute '{name}' or may have been annotated "
  221. f"wrongly."
  222. )
  223. return ObjectItemOperation.create(self, name, attribute_type).guess_type()
  224. else:
  225. return ObjectItemOperation.create(self, name).guess_type()
  226. def contains(self, key: Var | Any) -> BooleanVar:
  227. """Check if the object contains a key.
  228. Args:
  229. key: The key to check.
  230. Returns:
  231. The result of the check.
  232. """
  233. return object_has_own_property_operation(self, key)
  234. @dataclasses.dataclass(
  235. eq=False,
  236. frozen=True,
  237. **{"slots": True} if sys.version_info >= (3, 10) else {},
  238. )
  239. class LiteralObjectVar(CachedVarOperation, ObjectVar[OBJECT_TYPE], LiteralVar):
  240. """Base class for immutable literal object vars."""
  241. _var_value: Dict[Union[Var, Any], Union[Var, Any]] = dataclasses.field(
  242. default_factory=dict
  243. )
  244. def _key_type(self) -> Type:
  245. """Get the type of the keys of the object.
  246. Returns:
  247. The type of the keys of the object.
  248. """
  249. args_list = typing.get_args(self._var_type)
  250. return args_list[0] if args_list else Any
  251. def _value_type(self) -> Type:
  252. """Get the type of the values of the object.
  253. Returns:
  254. The type of the values of the object.
  255. """
  256. args_list = typing.get_args(self._var_type)
  257. return args_list[1] if args_list else Any
  258. @cached_property_no_lock
  259. def _cached_var_name(self) -> str:
  260. """The name of the var.
  261. Returns:
  262. The name of the var.
  263. """
  264. return (
  265. "({ "
  266. + ", ".join(
  267. [
  268. f"[{LiteralVar.create(key)!s}] : {LiteralVar.create(value)!s}"
  269. for key, value in self._var_value.items()
  270. ]
  271. )
  272. + " })"
  273. )
  274. def json(self) -> str:
  275. """Get the JSON representation of the object.
  276. Returns:
  277. The JSON representation of the object.
  278. """
  279. return (
  280. "{"
  281. + ", ".join(
  282. [
  283. f"{LiteralVar.create(key).json()}:{LiteralVar.create(value).json()}"
  284. for key, value in self._var_value.items()
  285. ]
  286. )
  287. + "}"
  288. )
  289. def __hash__(self) -> int:
  290. """Get the hash of the var.
  291. Returns:
  292. The hash of the var.
  293. """
  294. return hash((type(self).__name__, self._js_expr))
  295. @cached_property_no_lock
  296. def _cached_get_all_var_data(self) -> VarData | None:
  297. """Get all the var data.
  298. Returns:
  299. The var data.
  300. """
  301. return VarData.merge(
  302. *[LiteralVar.create(var)._get_all_var_data() for var in self._var_value],
  303. *[
  304. LiteralVar.create(var)._get_all_var_data()
  305. for var in self._var_value.values()
  306. ],
  307. self._var_data,
  308. )
  309. @classmethod
  310. def create(
  311. cls,
  312. _var_value: dict,
  313. _var_type: Type[OBJECT_TYPE] | None = None,
  314. _var_data: VarData | None = None,
  315. ) -> LiteralObjectVar[OBJECT_TYPE]:
  316. """Create the literal object var.
  317. Args:
  318. _var_value: The value of the var.
  319. _var_type: The type of the var.
  320. _var_data: Additional hooks and imports associated with the Var.
  321. Returns:
  322. The literal object var.
  323. """
  324. return LiteralObjectVar(
  325. _js_expr="",
  326. _var_type=(figure_out_type(_var_value) if _var_type is None else _var_type),
  327. _var_data=_var_data,
  328. _var_value=_var_value,
  329. )
  330. @var_operation
  331. def object_keys_operation(value: ObjectVar):
  332. """Get the keys of an object.
  333. Args:
  334. value: The object to get the keys from.
  335. Returns:
  336. The keys of the object.
  337. """
  338. return var_operation_return(
  339. js_expression=f"Object.keys({value})",
  340. var_type=List[str],
  341. )
  342. @var_operation
  343. def object_values_operation(value: ObjectVar):
  344. """Get the values of an object.
  345. Args:
  346. value: The object to get the values from.
  347. Returns:
  348. The values of the object.
  349. """
  350. return var_operation_return(
  351. js_expression=f"Object.values({value})",
  352. var_type=List[value._value_type()],
  353. )
  354. @var_operation
  355. def object_entries_operation(value: ObjectVar):
  356. """Get the entries of an object.
  357. Args:
  358. value: The object to get the entries from.
  359. Returns:
  360. The entries of the object.
  361. """
  362. return var_operation_return(
  363. js_expression=f"Object.entries({value})",
  364. var_type=List[Tuple[str, value._value_type()]],
  365. )
  366. @var_operation
  367. def object_merge_operation(lhs: ObjectVar, rhs: ObjectVar):
  368. """Merge two objects.
  369. Args:
  370. lhs: The first object to merge.
  371. rhs: The second object to merge.
  372. Returns:
  373. The merged object.
  374. """
  375. return var_operation_return(
  376. js_expression=f"({{...{lhs}, ...{rhs}}})",
  377. var_type=Dict[
  378. Union[lhs._key_type(), rhs._key_type()],
  379. Union[lhs._value_type(), rhs._value_type()],
  380. ],
  381. )
  382. @dataclasses.dataclass(
  383. eq=False,
  384. frozen=True,
  385. **{"slots": True} if sys.version_info >= (3, 10) else {},
  386. )
  387. class ObjectItemOperation(CachedVarOperation, Var):
  388. """Operation to get an item from an object."""
  389. _object: ObjectVar = dataclasses.field(
  390. default_factory=lambda: LiteralObjectVar.create({})
  391. )
  392. _key: Var | Any = dataclasses.field(default_factory=lambda: LiteralVar.create(None))
  393. @cached_property_no_lock
  394. def _cached_var_name(self) -> str:
  395. """The name of the operation.
  396. Returns:
  397. The name of the operation.
  398. """
  399. if types.is_optional(self._object._var_type):
  400. return f"{self._object!s}?.[{self._key!s}]"
  401. return f"{self._object!s}[{self._key!s}]"
  402. @classmethod
  403. def create(
  404. cls,
  405. object: ObjectVar,
  406. key: Var | Any,
  407. _var_type: GenericType | None = None,
  408. _var_data: VarData | None = None,
  409. ) -> ObjectItemOperation:
  410. """Create the object item operation.
  411. Args:
  412. object: The object to get the item from.
  413. key: The key to get from the object.
  414. _var_type: The type of the item.
  415. _var_data: Additional hooks and imports associated with the operation.
  416. Returns:
  417. The object item operation.
  418. """
  419. return cls(
  420. _js_expr="",
  421. _var_type=object._value_type() if _var_type is None else _var_type,
  422. _var_data=_var_data,
  423. _object=object,
  424. _key=key if isinstance(key, Var) else LiteralVar.create(key),
  425. )
  426. @var_operation
  427. def object_has_own_property_operation(object: ObjectVar, key: Var):
  428. """Check if an object has a key.
  429. Args:
  430. object: The object to check.
  431. key: The key to check.
  432. Returns:
  433. The result of the check.
  434. """
  435. return var_operation_return(
  436. js_expression=f"{object}.hasOwnProperty({key})",
  437. var_type=bool,
  438. )