types.py 11 KB

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