types.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import inspect
  6. import sys
  7. import types
  8. from functools import cached_property, lru_cache, wraps
  9. from typing import (
  10. Any,
  11. Callable,
  12. ClassVar,
  13. Dict,
  14. Iterable,
  15. List,
  16. Literal,
  17. Optional,
  18. Tuple,
  19. Type,
  20. Union,
  21. _GenericAlias, # type: ignore
  22. get_args,
  23. get_type_hints,
  24. )
  25. from typing import (
  26. get_origin as get_origin_og,
  27. )
  28. import sqlalchemy
  29. import reflex
  30. from reflex.components.core.breakpoints import Breakpoints
  31. try:
  32. from pydantic.v1.fields import ModelField
  33. except ModuleNotFoundError:
  34. from pydantic.fields import ModelField # type: ignore
  35. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  36. from sqlalchemy.ext.hybrid import hybrid_property
  37. from sqlalchemy.orm import (
  38. DeclarativeBase,
  39. Mapped,
  40. QueryableAttribute,
  41. Relationship,
  42. )
  43. from reflex import constants
  44. from reflex.base import Base
  45. from reflex.utils import console
  46. if sys.version_info >= (3, 12):
  47. from typing import override as override
  48. else:
  49. def override(func: Callable) -> Callable:
  50. """Fallback for @override decorator.
  51. Args:
  52. func: The function to decorate.
  53. Returns:
  54. The unmodified function.
  55. """
  56. return func
  57. # Potential GenericAlias types for isinstance checks.
  58. GenericAliasTypes = [_GenericAlias]
  59. with contextlib.suppress(ImportError):
  60. # For newer versions of Python.
  61. from types import GenericAlias # type: ignore
  62. GenericAliasTypes.append(GenericAlias)
  63. with contextlib.suppress(ImportError):
  64. # For older versions of Python.
  65. from typing import _SpecialGenericAlias # type: ignore
  66. GenericAliasTypes.append(_SpecialGenericAlias)
  67. GenericAliasTypes = tuple(GenericAliasTypes)
  68. # Potential Union types for isinstance checks (UnionType added in py3.10).
  69. UnionTypes = (Union, types.UnionType) if hasattr(types, "UnionType") else (Union,)
  70. # Union of generic types.
  71. GenericType = Union[Type, _GenericAlias]
  72. # Valid state var types.
  73. JSONType = {str, int, float, bool}
  74. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  75. StateVar = Union[PrimitiveType, Base, None]
  76. StateIterVar = Union[list, set, tuple]
  77. # ArgsSpec = Callable[[Var], list[Var]]
  78. ArgsSpec = Callable
  79. PrimitiveToAnnotation = {
  80. list: List,
  81. tuple: Tuple,
  82. dict: Dict,
  83. }
  84. RESERVED_BACKEND_VAR_NAMES = {
  85. "_abc_impl",
  86. "_backend_vars",
  87. "_was_touched",
  88. }
  89. if sys.version_info >= (3, 11):
  90. from typing import Self as Self
  91. else:
  92. from typing_extensions import Self as Self
  93. class Unset:
  94. """A class to represent an unset value.
  95. This is used to differentiate between a value that is not set and a value that is set to None.
  96. """
  97. def __repr__(self) -> str:
  98. """Return the string representation of the class.
  99. Returns:
  100. The string representation of the class.
  101. """
  102. return "Unset"
  103. def __bool__(self) -> bool:
  104. """Return False when the class is used in a boolean context.
  105. Returns:
  106. False
  107. """
  108. return False
  109. @lru_cache()
  110. def get_origin(tp):
  111. """Get the origin of a class.
  112. Args:
  113. tp: The class to get the origin of.
  114. Returns:
  115. The origin of the class.
  116. """
  117. return get_origin_og(tp)
  118. @lru_cache()
  119. def is_generic_alias(cls: GenericType) -> bool:
  120. """Check whether the class is a generic alias.
  121. Args:
  122. cls: The class to check.
  123. Returns:
  124. Whether the class is a generic alias.
  125. """
  126. return isinstance(cls, GenericAliasTypes)
  127. def is_none(cls: GenericType) -> bool:
  128. """Check if a class is None.
  129. Args:
  130. cls: The class to check.
  131. Returns:
  132. Whether the class is None.
  133. """
  134. return cls is type(None) or cls is None
  135. @lru_cache()
  136. def is_union(cls: GenericType) -> bool:
  137. """Check if a class is a Union.
  138. Args:
  139. cls: The class to check.
  140. Returns:
  141. Whether the class is a Union.
  142. """
  143. return get_origin(cls) in UnionTypes
  144. @lru_cache()
  145. def is_literal(cls: GenericType) -> bool:
  146. """Check if a class is a Literal.
  147. Args:
  148. cls: The class to check.
  149. Returns:
  150. Whether the class is a literal.
  151. """
  152. return get_origin(cls) is Literal
  153. def is_optional(cls: GenericType) -> bool:
  154. """Check if a class is an Optional.
  155. Args:
  156. cls: The class to check.
  157. Returns:
  158. Whether the class is an Optional.
  159. """
  160. return is_union(cls) and type(None) in get_args(cls)
  161. def get_property_hint(attr: Any | None) -> GenericType | None:
  162. """Check if an attribute is a property and return its type hint.
  163. Args:
  164. attr: The descriptor to check.
  165. Returns:
  166. The type hint of the property, if it is a property, else None.
  167. """
  168. if not isinstance(attr, (property, hybrid_property)):
  169. return None
  170. hints = get_type_hints(attr.fget)
  171. return hints.get("return", None)
  172. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  173. """Check if an attribute can be accessed on the cls and return its type.
  174. Supports pydantic models, unions, and annotated attributes on rx.Model.
  175. Args:
  176. cls: The class to check.
  177. name: The name of the attribute to check.
  178. Returns:
  179. The type of the attribute, if accessible, or None
  180. """
  181. from reflex.model import Model
  182. try:
  183. attr = getattr(cls, name, None)
  184. except NotImplementedError:
  185. attr = None
  186. if hint := get_property_hint(attr):
  187. return hint
  188. if (
  189. hasattr(cls, "__fields__")
  190. and name in cls.__fields__
  191. and hasattr(cls.__fields__[name], "outer_type_")
  192. ):
  193. # pydantic models
  194. field = cls.__fields__[name]
  195. type_ = field.outer_type_
  196. if isinstance(type_, ModelField):
  197. type_ = type_.type_
  198. if not field.required and field.default is None:
  199. # Ensure frontend uses null coalescing when accessing.
  200. type_ = Optional[type_]
  201. return type_
  202. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  203. insp = sqlalchemy.inspect(cls)
  204. if name in insp.columns:
  205. # check for list types
  206. column = insp.columns[name]
  207. column_type = column.type
  208. try:
  209. type_ = insp.columns[name].type.python_type
  210. except NotImplementedError:
  211. type_ = None
  212. if type_ is not None:
  213. if hasattr(column_type, "item_type"):
  214. try:
  215. item_type = column_type.item_type.python_type # type: ignore
  216. except NotImplementedError:
  217. item_type = None
  218. if item_type is not None:
  219. if type_ in PrimitiveToAnnotation:
  220. type_ = PrimitiveToAnnotation[type_] # type: ignore
  221. type_ = type_[item_type] # type: ignore
  222. if column.nullable:
  223. type_ = Optional[type_]
  224. return type_
  225. if name in insp.all_orm_descriptors:
  226. descriptor = insp.all_orm_descriptors[name]
  227. if hint := get_property_hint(descriptor):
  228. return hint
  229. if isinstance(descriptor, QueryableAttribute):
  230. prop = descriptor.property
  231. if isinstance(prop, Relationship):
  232. type_ = prop.mapper.class_
  233. # TODO: check for nullable?
  234. type_ = List[type_] if prop.uselist else Optional[type_]
  235. return type_
  236. if isinstance(attr, AssociationProxyInstance):
  237. return List[
  238. get_attribute_access_type(
  239. attr.target_class,
  240. attr.remote_attr.key, # type: ignore[attr-defined]
  241. )
  242. ]
  243. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  244. # Check in the annotations directly (for sqlmodel.Relationship)
  245. hints = get_type_hints(cls)
  246. if name in hints:
  247. type_ = hints[name]
  248. type_origin = get_origin(type_)
  249. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  250. return get_args(type_)[0] # SQLAlchemy v2
  251. if isinstance(type_, ModelField):
  252. return type_.type_ # SQLAlchemy v1.4
  253. return type_
  254. elif is_union(cls):
  255. # Check in each arg of the annotation.
  256. for arg in get_args(cls):
  257. type_ = get_attribute_access_type(arg, name)
  258. if type_ is not None:
  259. # Return the first attribute type that is accessible.
  260. return type_
  261. elif isinstance(cls, type):
  262. # Bare class
  263. if sys.version_info >= (3, 10):
  264. exceptions = NameError
  265. else:
  266. exceptions = (NameError, TypeError)
  267. try:
  268. hints = get_type_hints(cls)
  269. if name in hints:
  270. return hints[name]
  271. except exceptions as e:
  272. console.warn(f"Failed to resolve ForwardRefs for {cls}.{name} due to {e}")
  273. pass
  274. return None # Attribute is not accessible.
  275. @lru_cache()
  276. def get_base_class(cls: GenericType) -> Type:
  277. """Get the base class of a class.
  278. Args:
  279. cls: The class.
  280. Returns:
  281. The base class of the class.
  282. Raises:
  283. TypeError: If a literal has multiple types.
  284. """
  285. if is_literal(cls):
  286. # only literals of the same type are supported.
  287. arg_type = type(get_args(cls)[0])
  288. if not all(type(arg) == arg_type for arg in get_args(cls)):
  289. raise TypeError("only literals of the same type are supported")
  290. return type(get_args(cls)[0])
  291. if is_union(cls):
  292. return tuple(get_base_class(arg) for arg in get_args(cls))
  293. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  294. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  295. """Check if the breakpoints instance satisfies the typing.
  296. Args:
  297. cls_check: The class to check against.
  298. instance: The instance to check.
  299. Returns:
  300. Whether the breakpoints instance satisfies the typing.
  301. """
  302. cls_check_base = get_base_class(cls_check)
  303. if cls_check_base == Breakpoints:
  304. _, expected_type = get_args(cls_check)
  305. if is_literal(expected_type):
  306. for value in instance.values():
  307. if not isinstance(value, str) or value not in get_args(expected_type):
  308. return False
  309. return True
  310. elif isinstance(cls_check_base, tuple):
  311. # union type, so check all types
  312. return any(
  313. _breakpoints_satisfies_typing(type_to_check, instance)
  314. for type_to_check in get_args(cls_check)
  315. )
  316. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  317. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  318. return False
  319. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  320. """Check if a class is a subclass of another class.
  321. Args:
  322. cls: The class to check.
  323. cls_check: The class to check against.
  324. instance: An instance of cls to aid in checking generics.
  325. Returns:
  326. Whether the class is a subclass of the other class.
  327. Raises:
  328. TypeError: If the base class is not valid for issubclass.
  329. """
  330. # Special check for Any.
  331. if cls_check == Any:
  332. return True
  333. if cls in [Any, Callable, None]:
  334. return False
  335. # Get the base classes.
  336. cls_base = get_base_class(cls)
  337. cls_check_base = get_base_class(cls_check)
  338. # The class we're checking should not be a union.
  339. if isinstance(cls_base, tuple):
  340. return False
  341. # Check that fields of breakpoints match the expected values.
  342. if isinstance(instance, Breakpoints):
  343. return _breakpoints_satisfies_typing(cls_check, instance)
  344. # Check if the types match.
  345. try:
  346. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  347. except TypeError as te:
  348. # These errors typically arise from bad annotations and are hard to
  349. # debug without knowing the type that we tried to compare.
  350. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  351. def _isinstance(obj: Any, cls: GenericType) -> bool:
  352. """Check if an object is an instance of a class.
  353. Args:
  354. obj: The object to check.
  355. cls: The class to check against.
  356. Returns:
  357. Whether the object is an instance of the class.
  358. """
  359. return isinstance(obj, get_base_class(cls))
  360. def is_dataframe(value: Type) -> bool:
  361. """Check if the given value is a dataframe.
  362. Args:
  363. value: The value to check.
  364. Returns:
  365. Whether the value is a dataframe.
  366. """
  367. if is_generic_alias(value) or value == Any:
  368. return False
  369. return value.__name__ == "DataFrame"
  370. def is_valid_var_type(type_: Type) -> bool:
  371. """Check if the given type is a valid prop type.
  372. Args:
  373. type_: The type to check.
  374. Returns:
  375. Whether the type is a valid prop type.
  376. """
  377. from reflex.utils import serializers
  378. if is_union(type_):
  379. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  380. return (
  381. _issubclass(type_, StateVar)
  382. or serializers.has_serializer(type_)
  383. or dataclasses.is_dataclass(type_)
  384. )
  385. def is_backend_base_variable(name: str, cls: Type) -> bool:
  386. """Check if this variable name correspond to a backend variable.
  387. Args:
  388. name: The name of the variable to check
  389. cls: The class of the variable to check
  390. Returns:
  391. bool: The result of the check
  392. """
  393. if name in RESERVED_BACKEND_VAR_NAMES:
  394. return False
  395. if not name.startswith("_"):
  396. return False
  397. if name.startswith("__"):
  398. return False
  399. if name.startswith(f"_{cls.__name__}__"):
  400. return False
  401. hints = get_type_hints(cls)
  402. if name in hints:
  403. hint = get_origin(hints[name])
  404. if hint == ClassVar:
  405. return False
  406. if name in cls.inherited_backend_vars:
  407. return False
  408. from reflex.vars.base import is_computed_var
  409. if name in cls.__dict__:
  410. value = cls.__dict__[name]
  411. if type(value) == classmethod:
  412. return False
  413. if callable(value):
  414. return False
  415. if isinstance(
  416. value,
  417. (
  418. types.FunctionType,
  419. property,
  420. cached_property,
  421. ),
  422. ) or is_computed_var(value):
  423. return False
  424. return True
  425. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  426. """Check that a value type is found in a list of allowed types.
  427. Args:
  428. value_type: Type of value.
  429. allowed_types: Iterable of allowed types.
  430. Returns:
  431. If the type is found in the allowed types.
  432. """
  433. return get_base_class(value_type) in allowed_types
  434. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  435. """Check that a prop value is in a list of allowed types.
  436. Does the check in a way that works regardless if it's a raw value or a state Var.
  437. Args:
  438. prop: The prop to check.
  439. allowed_types: The list of allowed types.
  440. Returns:
  441. If the prop type match one of the allowed_types.
  442. """
  443. from reflex.vars import Var
  444. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  445. return type_ in allowed_types
  446. def is_encoded_fstring(value) -> bool:
  447. """Check if a value is an encoded Var f-string.
  448. Args:
  449. value: The value string to check.
  450. Returns:
  451. Whether the value is an f-string
  452. """
  453. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  454. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  455. """Check that a value is a valid literal.
  456. Args:
  457. key: The prop name.
  458. value: The prop value to validate.
  459. expected_type: The expected type(literal type).
  460. comp_name: Name of the component.
  461. Raises:
  462. ValueError: When the value is not a valid literal.
  463. """
  464. from reflex.vars import Var
  465. if (
  466. is_literal(expected_type)
  467. and not isinstance(value, Var) # validating vars is not supported yet.
  468. and not is_encoded_fstring(value) # f-strings are not supported.
  469. and value not in expected_type.__args__
  470. ):
  471. allowed_values = expected_type.__args__
  472. if value not in allowed_values:
  473. allowed_value_str = ",".join(
  474. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  475. )
  476. value_str = f"'{value}'" if isinstance(value, str) else value
  477. raise ValueError(
  478. f"prop value for {str(key)} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  479. )
  480. def validate_parameter_literals(func):
  481. """Decorator to check that the arguments passed to a function
  482. correspond to the correct function parameter if it (the parameter)
  483. is a literal type.
  484. Args:
  485. func: The function to validate.
  486. Returns:
  487. The wrapper function.
  488. """
  489. @wraps(func)
  490. def wrapper(*args, **kwargs):
  491. func_params = list(inspect.signature(func).parameters.items())
  492. annotations = {param[0]: param[1].annotation for param in func_params}
  493. # validate args
  494. for param, arg in zip(annotations, args):
  495. if annotations[param] is inspect.Parameter.empty:
  496. continue
  497. validate_literal(param, arg, annotations[param], func.__name__)
  498. # validate kwargs.
  499. for key, value in kwargs.items():
  500. annotation = annotations.get(key)
  501. if not annotation or annotation is inspect.Parameter.empty:
  502. continue
  503. validate_literal(key, value, annotation, func.__name__)
  504. return func(*args, **kwargs)
  505. return wrapper
  506. # Store this here for performance.
  507. StateBases = get_base_class(StateVar)
  508. StateIterBases = get_base_class(StateIterVar)