types.py 13 KB

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