types.py 7.2 KB

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