types.py 7.3 KB

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