types.py 8.0 KB

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