types.py 8.5 KB

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