types.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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.annotation
  92. if not field.is_required() and field.default is None:
  93. # Ensure frontend uses null coalescing when accessing.
  94. type_ = Optional[type_]
  95. return type_
  96. elif isinstance(cls, type) and issubclass(cls, Model):
  97. # Check in the annotations directly (for sqlmodel.Relationship)
  98. hints = get_type_hints(cls)
  99. if name in hints:
  100. type_ = hints[name]
  101. type_origin = get_origin(type_)
  102. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  103. return get_args(type_)[0] # SQLAlchemy v2
  104. raise RuntimeError("Pydantic V2 field type says what?")
  105. if isinstance(type_, ModelField):
  106. return type_.type_ # SQLAlchemy v1.4
  107. return type_
  108. elif is_union(cls):
  109. # Check in each arg of the annotation.
  110. for arg in get_args(cls):
  111. type_ = get_attribute_access_type(arg, name)
  112. if type_ is not None:
  113. # Return the first attribute type that is accessible.
  114. return type_
  115. return None # Attribute is not accessible.
  116. def get_base_class(cls: GenericType) -> Type:
  117. """Get the base class of a class.
  118. Args:
  119. cls: The class.
  120. Returns:
  121. The base class of the class.
  122. Raises:
  123. TypeError: If a literal has multiple types.
  124. """
  125. if is_literal(cls):
  126. # only literals of the same type are supported.
  127. arg_type = type(get_args(cls)[0])
  128. if not all(type(arg) == arg_type for arg in get_args(cls)):
  129. raise TypeError("only literals of the same type are supported")
  130. return type(get_args(cls)[0])
  131. if is_union(cls):
  132. return tuple(get_base_class(arg) for arg in get_args(cls))
  133. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  134. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  135. """Check if a class is a subclass of another class.
  136. Args:
  137. cls: The class to check.
  138. cls_check: The class to check against.
  139. Returns:
  140. Whether the class is a subclass of the other class.
  141. Raises:
  142. TypeError: If the base class is not valid for issubclass.
  143. """
  144. # Special check for Any.
  145. if cls_check == Any:
  146. return True
  147. if cls in [Any, Callable, None]:
  148. return False
  149. # Get the base classes.
  150. cls_base = get_base_class(cls)
  151. cls_check_base = get_base_class(cls_check)
  152. # The class we're checking should not be a union.
  153. if isinstance(cls_base, tuple):
  154. return False
  155. # Check if the types match.
  156. try:
  157. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  158. except TypeError as te:
  159. # These errors typically arise from bad annotations and are hard to
  160. # debug without knowing the type that we tried to compare.
  161. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  162. def _isinstance(obj: Any, cls: GenericType) -> bool:
  163. """Check if an object is an instance of a class.
  164. Args:
  165. obj: The object to check.
  166. cls: The class to check against.
  167. Returns:
  168. Whether the object is an instance of the class.
  169. """
  170. return isinstance(obj, get_base_class(cls))
  171. def is_dataframe(value: Type) -> bool:
  172. """Check if the given value is a dataframe.
  173. Args:
  174. value: The value to check.
  175. Returns:
  176. Whether the value is a dataframe.
  177. """
  178. if is_generic_alias(value) or value == Any:
  179. return False
  180. return value.__name__ == "DataFrame"
  181. def is_valid_var_type(type_: Type) -> bool:
  182. """Check if the given type is a valid prop type.
  183. Args:
  184. type_: The type to check.
  185. Returns:
  186. Whether the type is a valid prop type.
  187. """
  188. if is_union(type_):
  189. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  190. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  191. def is_backend_variable(name: str) -> bool:
  192. """Check if this variable name correspond to a backend variable.
  193. Args:
  194. name: The name of the variable to check
  195. Returns:
  196. bool: The result of the check
  197. """
  198. return name.startswith("_") and not name.startswith("__")
  199. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  200. """Check that a value type is found in a list of allowed types.
  201. Args:
  202. value_type: Type of value.
  203. allowed_types: Iterable of allowed types.
  204. Returns:
  205. If the type is found in the allowed types.
  206. """
  207. return get_base_class(value_type) in allowed_types
  208. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  209. """Check that a prop value is in a list of allowed types.
  210. Does the check in a way that works regardless if it's a raw value or a state Var.
  211. Args:
  212. prop: The prop to check.
  213. allowed_types: The list of allowed types.
  214. Returns:
  215. If the prop type match one of the allowed_types.
  216. """
  217. from reflex.vars import Var
  218. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  219. return type_ in allowed_types
  220. # Store this here for performance.
  221. StateBases = get_base_class(StateVar)
  222. StateIterBases = get_base_class(StateIterVar)