types.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import typing
  5. from typing import Any, Callable, Literal, Type, Union, _GenericAlias # type: ignore
  6. from reflex.base import Base
  7. from reflex.utils import serializers
  8. # Union of generic types.
  9. GenericType = Union[Type, _GenericAlias]
  10. # Valid state var types.
  11. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  12. StateVar = Union[PrimitiveType, Base, None]
  13. StateIterVar = Union[list, set, tuple]
  14. # ArgsSpec = Callable[[Var], list[Var]]
  15. ArgsSpec = Callable
  16. def get_args(alias: _GenericAlias) -> tuple[Type, ...]:
  17. """Get the arguments of a type alias.
  18. Args:
  19. alias: The type alias.
  20. Returns:
  21. The arguments of the type alias.
  22. """
  23. return alias.__args__
  24. def is_generic_alias(cls: GenericType) -> bool:
  25. """Check whether the class is a generic alias.
  26. Args:
  27. cls: The class to check.
  28. Returns:
  29. Whether the class is a generic alias.
  30. """
  31. # For older versions of Python.
  32. if isinstance(cls, _GenericAlias):
  33. return True
  34. with contextlib.suppress(ImportError):
  35. from typing import _SpecialGenericAlias # type: ignore
  36. if isinstance(cls, _SpecialGenericAlias):
  37. return True
  38. # For newer versions of Python.
  39. try:
  40. from types import GenericAlias # type: ignore
  41. return isinstance(cls, GenericAlias)
  42. except ImportError:
  43. return False
  44. def is_union(cls: GenericType) -> bool:
  45. """Check if a class is a Union.
  46. Args:
  47. cls: The class to check.
  48. Returns:
  49. Whether the class is a Union.
  50. """
  51. with contextlib.suppress(ImportError):
  52. from typing import _UnionGenericAlias # type: ignore
  53. return isinstance(cls, _UnionGenericAlias)
  54. return cls.__origin__ == Union if is_generic_alias(cls) else False
  55. def is_literal(cls: GenericType) -> bool:
  56. """Check if a class is a Literal.
  57. Args:
  58. cls: The class to check.
  59. Returns:
  60. Whether the class is a literal.
  61. """
  62. return hasattr(cls, "__origin__") and cls.__origin__ is Literal
  63. def get_base_class(cls: GenericType) -> Type:
  64. """Get the base class of a class.
  65. Args:
  66. cls: The class.
  67. Returns:
  68. The base class of the class.
  69. Raises:
  70. TypeError: If a literal has multiple types.
  71. """
  72. if is_literal(cls):
  73. # only literals of the same type are supported.
  74. arg_type = type(get_args(cls)[0])
  75. if not all(type(arg) == arg_type for arg in get_args(cls)):
  76. raise TypeError("only literals of the same type are supported")
  77. return type(get_args(cls)[0])
  78. if is_union(cls):
  79. return tuple(get_base_class(arg) for arg in get_args(cls))
  80. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  81. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  82. """Check if a class is a subclass of another class.
  83. Args:
  84. cls: The class to check.
  85. cls_check: The class to check against.
  86. Returns:
  87. Whether the class is a subclass of the other class.
  88. Raises:
  89. TypeError: If the base class is not valid for issubclass.
  90. """
  91. # Special check for Any.
  92. if cls_check == Any:
  93. return True
  94. if cls in [Any, Callable, None]:
  95. return False
  96. # Get the base classes.
  97. cls_base = get_base_class(cls)
  98. cls_check_base = get_base_class(cls_check)
  99. # The class we're checking should not be a union.
  100. if isinstance(cls_base, tuple):
  101. return False
  102. # Check if the types match.
  103. try:
  104. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  105. except TypeError as te:
  106. # These errors typically arise from bad annotations and are hard to
  107. # debug without knowing the type that we tried to compare.
  108. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  109. def _isinstance(obj: Any, cls: GenericType) -> bool:
  110. """Check if an object is an instance of a class.
  111. Args:
  112. obj: The object to check.
  113. cls: The class to check against.
  114. Returns:
  115. Whether the object is an instance of the class.
  116. """
  117. return isinstance(obj, get_base_class(cls))
  118. def is_dataframe(value: Type) -> bool:
  119. """Check if the given value is a dataframe.
  120. Args:
  121. value: The value to check.
  122. Returns:
  123. Whether the value is a dataframe.
  124. """
  125. if is_generic_alias(value) or value == typing.Any:
  126. return False
  127. return value.__name__ == "DataFrame"
  128. def is_valid_var_type(type_: Type) -> bool:
  129. """Check if the given type is a valid prop type.
  130. Args:
  131. type_: The type to check.
  132. Returns:
  133. Whether the type is a valid prop type.
  134. """
  135. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  136. def is_backend_variable(name: str) -> bool:
  137. """Check if this variable name correspond to a backend variable.
  138. Args:
  139. name: The name of the variable to check
  140. Returns:
  141. bool: The result of the check
  142. """
  143. return name.startswith("_") and not name.startswith("__")
  144. def check_type_in_allowed_types(
  145. value_type: Type, allowed_types: typing.Iterable
  146. ) -> bool:
  147. """Check that a value type is found in a list of allowed types.
  148. Args:
  149. value_type: Type of value.
  150. allowed_types: Iterable of allowed types.
  151. Returns:
  152. If the type is found in the allowed types.
  153. """
  154. return get_base_class(value_type) in allowed_types
  155. # Store this here for performance.
  156. StateBases = get_base_class(StateVar)
  157. StateIterBases = get_base_class(StateIterVar)