types.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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, 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 get_base_class(cls: GenericType) -> Type:
  56. """Get the base class of a class.
  57. Args:
  58. cls: The class.
  59. Returns:
  60. The base class of the class.
  61. """
  62. if is_union(cls):
  63. return tuple(get_base_class(arg) for arg in get_args(cls))
  64. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  65. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  66. """Check if a class is a subclass of another class.
  67. Args:
  68. cls: The class to check.
  69. cls_check: The class to check against.
  70. Returns:
  71. Whether the class is a subclass of the other class.
  72. Raises:
  73. TypeError: If the base class is not valid for issubclass.
  74. """
  75. # Special check for Any.
  76. if cls_check == Any:
  77. return True
  78. if cls in [Any, Callable, None]:
  79. return False
  80. # Get the base classes.
  81. cls_base = get_base_class(cls)
  82. cls_check_base = get_base_class(cls_check)
  83. # The class we're checking should not be a union.
  84. if isinstance(cls_base, tuple):
  85. return False
  86. # Check if the types match.
  87. try:
  88. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  89. except TypeError as te:
  90. # These errors typically arise from bad annotations and are hard to
  91. # debug without knowing the type that we tried to compare.
  92. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  93. def _isinstance(obj: Any, cls: GenericType) -> bool:
  94. """Check if an object is an instance of a class.
  95. Args:
  96. obj: The object to check.
  97. cls: The class to check against.
  98. Returns:
  99. Whether the object is an instance of the class.
  100. """
  101. return isinstance(obj, get_base_class(cls))
  102. def is_dataframe(value: Type) -> bool:
  103. """Check if the given value is a dataframe.
  104. Args:
  105. value: The value to check.
  106. Returns:
  107. Whether the value is a dataframe.
  108. """
  109. if is_generic_alias(value) or value == typing.Any:
  110. return False
  111. return value.__name__ == "DataFrame"
  112. def is_valid_var_type(type_: Type) -> bool:
  113. """Check if the given type is a valid prop type.
  114. Args:
  115. type_: The type to check.
  116. Returns:
  117. Whether the type is a valid prop type.
  118. """
  119. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  120. def is_backend_variable(name: str) -> bool:
  121. """Check if this variable name correspond to a backend variable.
  122. Args:
  123. name: The name of the variable to check
  124. Returns:
  125. bool: The result of the check
  126. """
  127. return name.startswith("_") and not name.startswith("__")
  128. def check_type_in_allowed_types(
  129. value_type: Type, allowed_types: typing.Iterable
  130. ) -> bool:
  131. """Check that a value type is found in a list of allowed types.
  132. Args:
  133. value_type: Type of value.
  134. allowed_types: Iterable of allowed types.
  135. Returns:
  136. If the type is found in the allowed types.
  137. """
  138. return get_base_class(value_type) in allowed_types
  139. # Store this here for performance.
  140. StateBases = get_base_class(StateVar)
  141. StateIterBases = get_base_class(StateIterVar)