types.py 9.4 KB

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