types.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import typing
  5. from types import LambdaType
  6. from typing import Any, Callable, Type, Union, _GenericAlias # type: ignore
  7. from reflex.base import Base
  8. from reflex.utils import serializers
  9. # Union of generic types.
  10. GenericType = Union[Type, _GenericAlias]
  11. # Valid state var types.
  12. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  13. StateVar = Union[PrimitiveType, Base, None]
  14. StateIterVar = Union[list, set, tuple]
  15. ArgsSpec = LambdaType
  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. """
  73. # Special check for Any.
  74. if cls_check == Any:
  75. return True
  76. if cls in [Any, Callable, None]:
  77. return False
  78. # Get the base classes.
  79. cls_base = get_base_class(cls)
  80. cls_check_base = get_base_class(cls_check)
  81. # The class we're checking should not be a union.
  82. if isinstance(cls_base, tuple):
  83. return False
  84. # Check if the types match.
  85. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  86. def _isinstance(obj: Any, cls: GenericType) -> bool:
  87. """Check if an object is an instance of a class.
  88. Args:
  89. obj: The object to check.
  90. cls: The class to check against.
  91. Returns:
  92. Whether the object is an instance of the class.
  93. """
  94. return isinstance(obj, get_base_class(cls))
  95. def is_dataframe(value: Type) -> bool:
  96. """Check if the given value is a dataframe.
  97. Args:
  98. value: The value to check.
  99. Returns:
  100. Whether the value is a dataframe.
  101. """
  102. if is_generic_alias(value) or value == typing.Any:
  103. return False
  104. return value.__name__ == "DataFrame"
  105. def is_valid_var_type(type_: Type) -> bool:
  106. """Check if the given type is a valid prop type.
  107. Args:
  108. type_: The type to check.
  109. Returns:
  110. Whether the type is a valid prop type.
  111. """
  112. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  113. def is_backend_variable(name: str) -> bool:
  114. """Check if this variable name correspond to a backend variable.
  115. Args:
  116. name: The name of the variable to check
  117. Returns:
  118. bool: The result of the check
  119. """
  120. return name.startswith("_") and not name.startswith("__")
  121. # Store this here for performance.
  122. StateBases = get_base_class(StateVar)
  123. StateIterBases = get_base_class(StateIterVar)