object.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. ClassVar,
  10. Dict,
  11. List,
  12. NoReturn,
  13. Tuple,
  14. Type,
  15. TypeVar,
  16. Union,
  17. get_args,
  18. overload,
  19. )
  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. ToOperation,
  27. Var,
  28. VarData,
  29. cached_property_no_lock,
  30. figure_out_type,
  31. var_operation,
  32. var_operation_return,
  33. )
  34. from .number import BooleanVar, NumberVar, raise_unsupported_operand_types
  35. from .sequence import ArrayVar, StringVar
  36. OBJECT_TYPE = TypeVar("OBJECT_TYPE", bound=Dict)
  37. KEY_TYPE = TypeVar("KEY_TYPE")
  38. VALUE_TYPE = TypeVar("VALUE_TYPE")
  39. ARRAY_INNER_TYPE = TypeVar("ARRAY_INNER_TYPE")
  40. OTHER_KEY_TYPE = TypeVar("OTHER_KEY_TYPE")
  41. class ObjectVar(Var[OBJECT_TYPE]):
  42. """Base class for immutable object vars."""
  43. def _key_type(self) -> Type:
  44. """Get the type of the keys of the object.
  45. Returns:
  46. The type of the keys of the object.
  47. """
  48. return str
  49. @overload
  50. def _value_type(
  51. self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
  52. ) -> Type[VALUE_TYPE]: ...
  53. @overload
  54. def _value_type(self) -> Type: ...
  55. def _value_type(self) -> Type:
  56. """Get the type of the values of the object.
  57. Returns:
  58. The type of the values of the object.
  59. """
  60. fixed_type = get_origin(self._var_type) or self._var_type
  61. if not isclass(fixed_type):
  62. return Any
  63. args = get_args(self._var_type) if issubclass(fixed_type, dict) else ()
  64. return args[1] if args else Any
  65. def keys(self) -> ArrayVar[List[str]]:
  66. """Get the keys of the object.
  67. Returns:
  68. The keys of the object.
  69. """
  70. return object_keys_operation(self)
  71. @overload
  72. def values(
  73. self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
  74. ) -> ArrayVar[List[VALUE_TYPE]]: ...
  75. @overload
  76. def values(self) -> ArrayVar: ...
  77. def values(self) -> ArrayVar:
  78. """Get the values of the object.
  79. Returns:
  80. The values of the object.
  81. """
  82. return object_values_operation(self)
  83. @overload
  84. def entries(
  85. self: ObjectVar[Dict[KEY_TYPE, VALUE_TYPE]],
  86. ) -> ArrayVar[List[Tuple[str, VALUE_TYPE]]]: ...
  87. @overload
  88. def entries(self) -> ArrayVar: ...
  89. def entries(self) -> ArrayVar:
  90. """Get the entries of the object.
  91. Returns:
  92. The entries of the object.
  93. """
  94. return object_entries_operation(self)
  95. items = entries
  96. def merge(self, other: ObjectVar):
  97. """Merge two objects.
  98. Args:
  99. other: The other object to merge.
  100. Returns:
  101. The merged object.
  102. """
  103. return object_merge_operation(self, other)
  104. # NoReturn is used here to catch when key value is Any
  105. @overload
  106. def __getitem__(
  107. self: ObjectVar[Dict[KEY_TYPE, NoReturn]],
  108. key: Var | Any,
  109. ) -> Var: ...
  110. @overload
  111. def __getitem__(
  112. self: (
  113. ObjectVar[Dict[KEY_TYPE, int]]
  114. | ObjectVar[Dict[KEY_TYPE, float]]
  115. | ObjectVar[Dict[KEY_TYPE, int | float]]
  116. ),
  117. key: Var | Any,
  118. ) -> NumberVar: ...
  119. @overload
  120. def __getitem__(
  121. self: ObjectVar[Dict[KEY_TYPE, str]],
  122. key: Var | Any,
  123. ) -> StringVar: ...
  124. @overload
  125. def __getitem__(
  126. self: ObjectVar[Dict[KEY_TYPE, list[ARRAY_INNER_TYPE]]],
  127. key: Var | Any,
  128. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  129. @overload
  130. def __getitem__(
  131. self: ObjectVar[Dict[KEY_TYPE, set[ARRAY_INNER_TYPE]]],
  132. key: Var | Any,
  133. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  134. @overload
  135. def __getitem__(
  136. self: ObjectVar[Dict[KEY_TYPE, tuple[ARRAY_INNER_TYPE, ...]]],
  137. key: Var | Any,
  138. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  139. @overload
  140. def __getitem__(
  141. self: ObjectVar[Dict[KEY_TYPE, dict[OTHER_KEY_TYPE, VALUE_TYPE]]],
  142. key: Var | Any,
  143. ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
  144. def __getitem__(self, key: Var | Any) -> Var:
  145. """Get an item from the object.
  146. Args:
  147. key: The key to get from the object.
  148. Returns:
  149. The item from the object.
  150. """
  151. if not isinstance(key, (StringVar, str, int, NumberVar)) or (
  152. isinstance(key, NumberVar) and key._is_strict_float()
  153. ):
  154. raise_unsupported_operand_types("[]", (type(self), type(key)))
  155. return ObjectItemOperation.create(self, key).guess_type()
  156. # NoReturn is used here to catch when key value is Any
  157. @overload
  158. def __getattr__(
  159. self: ObjectVar[Dict[KEY_TYPE, NoReturn]],
  160. name: str,
  161. ) -> Var: ...
  162. @overload
  163. def __getattr__(
  164. self: (
  165. ObjectVar[Dict[KEY_TYPE, int]]
  166. | ObjectVar[Dict[KEY_TYPE, float]]
  167. | ObjectVar[Dict[KEY_TYPE, int | float]]
  168. ),
  169. name: str,
  170. ) -> NumberVar: ...
  171. @overload
  172. def __getattr__(
  173. self: ObjectVar[Dict[KEY_TYPE, str]],
  174. name: str,
  175. ) -> StringVar: ...
  176. @overload
  177. def __getattr__(
  178. self: ObjectVar[Dict[KEY_TYPE, list[ARRAY_INNER_TYPE]]],
  179. name: str,
  180. ) -> ArrayVar[list[ARRAY_INNER_TYPE]]: ...
  181. @overload
  182. def __getattr__(
  183. self: ObjectVar[Dict[KEY_TYPE, set[ARRAY_INNER_TYPE]]],
  184. name: str,
  185. ) -> ArrayVar[set[ARRAY_INNER_TYPE]]: ...
  186. @overload
  187. def __getattr__(
  188. self: ObjectVar[Dict[KEY_TYPE, tuple[ARRAY_INNER_TYPE, ...]]],
  189. name: str,
  190. ) -> ArrayVar[tuple[ARRAY_INNER_TYPE, ...]]: ...
  191. @overload
  192. def __getattr__(
  193. self: ObjectVar[Dict[KEY_TYPE, dict[OTHER_KEY_TYPE, VALUE_TYPE]]],
  194. name: str,
  195. ) -> ObjectVar[dict[OTHER_KEY_TYPE, VALUE_TYPE]]: ...
  196. def __getattr__(self, name) -> Var:
  197. """Get an attribute of the var.
  198. Args:
  199. name: The name of the attribute.
  200. Raises:
  201. VarAttributeError: The State var has no such attribute or may have been annotated wrongly.
  202. Returns:
  203. The attribute of the var.
  204. """
  205. if name.startswith("__") and name.endswith("__"):
  206. return getattr(super(type(self), self), name)
  207. var_type = self._var_type
  208. if types.is_optional(var_type):
  209. var_type = get_args(var_type)[0]
  210. fixed_type = var_type if isclass(var_type) else get_origin(var_type)
  211. if isclass(fixed_type) and not issubclass(fixed_type, dict):
  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. @dataclasses.dataclass(
  422. eq=False,
  423. frozen=True,
  424. **{"slots": True} if sys.version_info >= (3, 10) else {},
  425. )
  426. class ToObjectOperation(ToOperation, ObjectVar):
  427. """Operation to convert a var to an object."""
  428. _original: Var = dataclasses.field(
  429. default_factory=lambda: LiteralObjectVar.create({})
  430. )
  431. _default_var_type: ClassVar[GenericType] = dict
  432. def __getattr__(self, name: str) -> Any:
  433. """Get an attribute of the var.
  434. Args:
  435. name: The name of the attribute.
  436. Returns:
  437. The attribute of the var.
  438. """
  439. if name == "_js_expr":
  440. return self._original._js_expr
  441. return ObjectVar.__getattr__(self, name)
  442. @var_operation
  443. def object_has_own_property_operation(object: ObjectVar, key: Var):
  444. """Check if an object has a key.
  445. Args:
  446. object: The object to check.
  447. key: The key to check.
  448. Returns:
  449. The result of the check.
  450. """
  451. return var_operation_return(
  452. js_expression=f"{object}.hasOwnProperty({key})",
  453. var_type=bool,
  454. )