types.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import inspect
  5. import types
  6. from functools import wraps
  7. from typing import (
  8. TYPE_CHECKING,
  9. Any,
  10. Callable,
  11. Iterable,
  12. List,
  13. Literal,
  14. Optional,
  15. Type,
  16. Union,
  17. _GenericAlias, # type: ignore
  18. get_args,
  19. get_origin,
  20. get_type_hints,
  21. )
  22. import sqlalchemy
  23. try:
  24. # TODO The type checking guard can be removed once
  25. # reflex-hosting-cli tools are compatible with pydantic v2
  26. if not TYPE_CHECKING:
  27. from pydantic.v1.fields import ModelField
  28. else:
  29. raise ModuleNotFoundError
  30. except ModuleNotFoundError:
  31. from pydantic.fields import ModelField
  32. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  33. from sqlalchemy.ext.hybrid import hybrid_property
  34. from sqlalchemy.orm import DeclarativeBase, Mapped, QueryableAttribute, Relationship
  35. from reflex import constants
  36. from reflex.base import Base
  37. from reflex.utils import serializers
  38. # Potential GenericAlias types for isinstance checks.
  39. GenericAliasTypes = [_GenericAlias]
  40. with contextlib.suppress(ImportError):
  41. # For newer versions of Python.
  42. from types import GenericAlias # type: ignore
  43. GenericAliasTypes.append(GenericAlias)
  44. with contextlib.suppress(ImportError):
  45. # For older versions of Python.
  46. from typing import _SpecialGenericAlias # type: ignore
  47. GenericAliasTypes.append(_SpecialGenericAlias)
  48. GenericAliasTypes = tuple(GenericAliasTypes)
  49. # Potential Union types for isinstance checks (UnionType added in py3.10).
  50. UnionTypes = (Union, types.UnionType) if hasattr(types, "UnionType") else (Union,)
  51. # Union of generic types.
  52. GenericType = Union[Type, _GenericAlias]
  53. # Valid state var types.
  54. JSONType = {str, int, float, bool}
  55. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  56. StateVar = Union[PrimitiveType, Base, None]
  57. StateIterVar = Union[list, set, tuple]
  58. # ArgsSpec = Callable[[Var], list[Var]]
  59. ArgsSpec = Callable
  60. class Unset:
  61. """A class to represent an unset value.
  62. This is used to differentiate between a value that is not set and a value that is set to None.
  63. """
  64. def __repr__(self) -> str:
  65. """Return the string representation of the class.
  66. Returns:
  67. The string representation of the class.
  68. """
  69. return "Unset"
  70. def __bool__(self) -> bool:
  71. """Return False when the class is used in a boolean context.
  72. Returns:
  73. False
  74. """
  75. return False
  76. def is_generic_alias(cls: GenericType) -> bool:
  77. """Check whether the class is a generic alias.
  78. Args:
  79. cls: The class to check.
  80. Returns:
  81. Whether the class is a generic alias.
  82. """
  83. return isinstance(cls, GenericAliasTypes)
  84. def is_union(cls: GenericType) -> bool:
  85. """Check if a class is a Union.
  86. Args:
  87. cls: The class to check.
  88. Returns:
  89. Whether the class is a Union.
  90. """
  91. return get_origin(cls) in UnionTypes
  92. def is_literal(cls: GenericType) -> bool:
  93. """Check if a class is a Literal.
  94. Args:
  95. cls: The class to check.
  96. Returns:
  97. Whether the class is a literal.
  98. """
  99. return get_origin(cls) is Literal
  100. def is_optional(cls: GenericType) -> bool:
  101. """Check if a class is an Optional.
  102. Args:
  103. cls: The class to check.
  104. Returns:
  105. Whether the class is an Optional.
  106. """
  107. return is_union(cls) and type(None) in get_args(cls)
  108. def get_property_hint(attr: Any | None) -> GenericType | None:
  109. """Check if an attribute is a property and return its type hint.
  110. Args:
  111. attr: The descriptor to check.
  112. Returns:
  113. The type hint of the property, if it is a property, else None.
  114. """
  115. if not isinstance(attr, (property, hybrid_property)):
  116. return None
  117. hints = get_type_hints(attr.fget)
  118. return hints.get("return", None)
  119. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  120. """Check if an attribute can be accessed on the cls and return its type.
  121. Supports pydantic models, unions, and annotated attributes on rx.Model.
  122. Args:
  123. cls: The class to check.
  124. name: The name of the attribute to check.
  125. Returns:
  126. The type of the attribute, if accessible, or None
  127. """
  128. from reflex.model import Model
  129. attr = getattr(cls, name, None)
  130. if hint := get_property_hint(attr):
  131. return hint
  132. if hasattr(cls, "__fields__") and name in cls.__fields__:
  133. # pydantic models
  134. field = cls.__fields__[name]
  135. type_ = field.outer_type_
  136. if isinstance(type_, ModelField):
  137. type_ = type_.type_
  138. if not field.required and field.default is None:
  139. # Ensure frontend uses null coalescing when accessing.
  140. type_ = Optional[type_]
  141. return type_
  142. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  143. insp = sqlalchemy.inspect(cls)
  144. if name in insp.columns:
  145. return insp.columns[name].type.python_type
  146. if name not in insp.all_orm_descriptors.keys():
  147. return None
  148. descriptor = insp.all_orm_descriptors[name]
  149. if hint := get_property_hint(descriptor):
  150. return hint
  151. if isinstance(descriptor, QueryableAttribute):
  152. prop = descriptor.property
  153. if not isinstance(prop, Relationship):
  154. return None
  155. class_ = prop.mapper.class_
  156. if prop.uselist:
  157. return List[class_]
  158. else:
  159. return class_
  160. if isinstance(attr, AssociationProxyInstance):
  161. return List[
  162. get_attribute_access_type(
  163. attr.target_class,
  164. attr.remote_attr.key, # type: ignore[attr-defined]
  165. )
  166. ]
  167. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  168. # Check in the annotations directly (for sqlmodel.Relationship)
  169. hints = get_type_hints(cls)
  170. if name in hints:
  171. type_ = hints[name]
  172. type_origin = get_origin(type_)
  173. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  174. return get_args(type_)[0] # SQLAlchemy v2
  175. if isinstance(type_, ModelField):
  176. return type_.type_ # SQLAlchemy v1.4
  177. return type_
  178. elif is_union(cls):
  179. # Check in each arg of the annotation.
  180. for arg in get_args(cls):
  181. type_ = get_attribute_access_type(arg, name)
  182. if type_ is not None:
  183. # Return the first attribute type that is accessible.
  184. return type_
  185. return None # Attribute is not accessible.
  186. def get_base_class(cls: GenericType) -> Type:
  187. """Get the base class of a class.
  188. Args:
  189. cls: The class.
  190. Returns:
  191. The base class of the class.
  192. Raises:
  193. TypeError: If a literal has multiple types.
  194. """
  195. if is_literal(cls):
  196. # only literals of the same type are supported.
  197. arg_type = type(get_args(cls)[0])
  198. if not all(type(arg) == arg_type for arg in get_args(cls)):
  199. raise TypeError("only literals of the same type are supported")
  200. return type(get_args(cls)[0])
  201. if is_union(cls):
  202. return tuple(get_base_class(arg) for arg in get_args(cls))
  203. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  204. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  205. """Check if a class is a subclass of another class.
  206. Args:
  207. cls: The class to check.
  208. cls_check: The class to check against.
  209. Returns:
  210. Whether the class is a subclass of the other class.
  211. Raises:
  212. TypeError: If the base class is not valid for issubclass.
  213. """
  214. # Special check for Any.
  215. if cls_check == Any:
  216. return True
  217. if cls in [Any, Callable, None]:
  218. return False
  219. # Get the base classes.
  220. cls_base = get_base_class(cls)
  221. cls_check_base = get_base_class(cls_check)
  222. # The class we're checking should not be a union.
  223. if isinstance(cls_base, tuple):
  224. return False
  225. # Check if the types match.
  226. try:
  227. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  228. except TypeError as te:
  229. # These errors typically arise from bad annotations and are hard to
  230. # debug without knowing the type that we tried to compare.
  231. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  232. def _isinstance(obj: Any, cls: GenericType) -> bool:
  233. """Check if an object is an instance of a class.
  234. Args:
  235. obj: The object to check.
  236. cls: The class to check against.
  237. Returns:
  238. Whether the object is an instance of the class.
  239. """
  240. return isinstance(obj, get_base_class(cls))
  241. def is_dataframe(value: Type) -> bool:
  242. """Check if the given value is a dataframe.
  243. Args:
  244. value: The value to check.
  245. Returns:
  246. Whether the value is a dataframe.
  247. """
  248. if is_generic_alias(value) or value == Any:
  249. return False
  250. return value.__name__ == "DataFrame"
  251. def is_valid_var_type(type_: Type) -> bool:
  252. """Check if the given type is a valid prop type.
  253. Args:
  254. type_: The type to check.
  255. Returns:
  256. Whether the type is a valid prop type.
  257. """
  258. if is_union(type_):
  259. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  260. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  261. def is_backend_variable(name: str, cls: Type | None = None) -> bool:
  262. """Check if this variable name correspond to a backend variable.
  263. Args:
  264. name: The name of the variable to check
  265. cls: The class of the variable to check
  266. Returns:
  267. bool: The result of the check
  268. """
  269. if cls is not None and name.startswith(f"_{cls.__name__}__"):
  270. return False
  271. return name.startswith("_") and not name.startswith("__")
  272. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  273. """Check that a value type is found in a list of allowed types.
  274. Args:
  275. value_type: Type of value.
  276. allowed_types: Iterable of allowed types.
  277. Returns:
  278. If the type is found in the allowed types.
  279. """
  280. return get_base_class(value_type) in allowed_types
  281. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  282. """Check that a prop value is in a list of allowed types.
  283. Does the check in a way that works regardless if it's a raw value or a state Var.
  284. Args:
  285. prop: The prop to check.
  286. allowed_types: The list of allowed types.
  287. Returns:
  288. If the prop type match one of the allowed_types.
  289. """
  290. from reflex.vars import Var
  291. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  292. return type_ in allowed_types
  293. def is_encoded_fstring(value) -> bool:
  294. """Check if a value is an encoded Var f-string.
  295. Args:
  296. value: The value string to check.
  297. Returns:
  298. Whether the value is an f-string
  299. """
  300. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  301. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  302. """Check that a value is a valid literal.
  303. Args:
  304. key: The prop name.
  305. value: The prop value to validate.
  306. expected_type: The expected type(literal type).
  307. comp_name: Name of the component.
  308. Raises:
  309. ValueError: When the value is not a valid literal.
  310. """
  311. from reflex.vars import Var
  312. if (
  313. is_literal(expected_type)
  314. and not isinstance(value, Var) # validating vars is not supported yet.
  315. and not is_encoded_fstring(value) # f-strings are not supported.
  316. and value not in expected_type.__args__
  317. ):
  318. allowed_values = expected_type.__args__
  319. if value not in allowed_values:
  320. allowed_value_str = ",".join(
  321. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  322. )
  323. value_str = f"'{value}'" if isinstance(value, str) else value
  324. raise ValueError(
  325. f"prop value for {str(key)} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  326. )
  327. def validate_parameter_literals(func):
  328. """Decorator to check that the arguments passed to a function
  329. correspond to the correct function parameter if it (the parameter)
  330. is a literal type.
  331. Args:
  332. func: The function to validate.
  333. Returns:
  334. The wrapper function.
  335. """
  336. @wraps(func)
  337. def wrapper(*args, **kwargs):
  338. func_params = list(inspect.signature(func).parameters.items())
  339. annotations = {param[0]: param[1].annotation for param in func_params}
  340. # validate args
  341. for param, arg in zip(annotations.keys(), args):
  342. if annotations[param] is inspect.Parameter.empty:
  343. continue
  344. validate_literal(param, arg, annotations[param], func.__name__)
  345. # validate kwargs.
  346. for key, value in kwargs.items():
  347. annotation = annotations.get(key)
  348. if not annotation or annotation is inspect.Parameter.empty:
  349. continue
  350. validate_literal(key, value, annotation, func.__name__)
  351. return func(*args, **kwargs)
  352. return wrapper
  353. # Store this here for performance.
  354. StateBases = get_base_class(StateVar)
  355. StateIterBases = get_base_class(StateIterVar)