types.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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, Tuple, Type, Union, _GenericAlias # type: ignore
  6. from pynecone.base import Base
  7. # Union of generic types.
  8. GenericType = Union[Type, _GenericAlias]
  9. # Valid state var types.
  10. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  11. StateVar = Union[PrimitiveType, Base, None]
  12. def get_args(alias: _GenericAlias) -> Tuple[Type, ...]:
  13. """Get the arguments of a type alias.
  14. Args:
  15. alias: The type alias.
  16. Returns:
  17. The arguments of the type alias.
  18. """
  19. return alias.__args__
  20. def is_generic_alias(cls: GenericType) -> bool:
  21. """Check whether the class is a generic alias.
  22. Args:
  23. cls: The class to check.
  24. Returns:
  25. Whether the class is a generic alias.
  26. """
  27. # For older versions of Python.
  28. if isinstance(cls, _GenericAlias):
  29. return True
  30. with contextlib.suppress(ImportError):
  31. from typing import _SpecialGenericAlias # type: ignore
  32. if isinstance(cls, _SpecialGenericAlias):
  33. return True
  34. # For newer versions of Python.
  35. try:
  36. from types import GenericAlias # type: ignore
  37. return isinstance(cls, GenericAlias)
  38. except ImportError:
  39. return False
  40. def is_union(cls: GenericType) -> bool:
  41. """Check if a class is a Union.
  42. Args:
  43. cls: The class to check.
  44. Returns:
  45. Whether the class is a Union.
  46. """
  47. with contextlib.suppress(ImportError):
  48. from typing import _UnionGenericAlias # type: ignore
  49. return isinstance(cls, _UnionGenericAlias)
  50. return cls.__origin__ == Union if is_generic_alias(cls) else False
  51. def get_base_class(cls: GenericType) -> Type:
  52. """Get the base class of a class.
  53. Args:
  54. cls: The class.
  55. Returns:
  56. The base class of the class.
  57. """
  58. if is_union(cls):
  59. return tuple(get_base_class(arg) for arg in get_args(cls))
  60. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  61. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  62. """Check if a class is a subclass of another class.
  63. Args:
  64. cls: The class to check.
  65. cls_check: The class to check against.
  66. Returns:
  67. Whether the class is a subclass of the other class.
  68. """
  69. # Special check for Any.
  70. if cls_check == Any:
  71. return True
  72. if cls in [Any, Callable]:
  73. return False
  74. # Get the base classes.
  75. cls_base = get_base_class(cls)
  76. cls_check_base = get_base_class(cls_check)
  77. # The class we're checking should not be a union.
  78. if isinstance(cls_base, tuple):
  79. return False
  80. # Check if the types match.
  81. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  82. def _isinstance(obj: Any, cls: GenericType) -> bool:
  83. """Check if an object is an instance of a class.
  84. Args:
  85. obj: The object to check.
  86. cls: The class to check against.
  87. Returns:
  88. Whether the object is an instance of the class.
  89. """
  90. return isinstance(obj, get_base_class(cls))
  91. def is_dataframe(value: Type) -> bool:
  92. """Check if the given value is a dataframe.
  93. Args:
  94. value: The value to check.
  95. Returns:
  96. Whether the value is a dataframe.
  97. """
  98. if is_generic_alias(value) or value == typing.Any:
  99. return False
  100. return value.__name__ == "DataFrame"
  101. def is_image(value: Type) -> bool:
  102. """Check if the given value is a pillow image. By checking if the value subclasses PIL.
  103. Args:
  104. value: The value to check.
  105. Returns:
  106. Whether the value is a pillow image.
  107. """
  108. if is_generic_alias(value) or value == typing.Any:
  109. return False
  110. return "PIL" in value.__module__
  111. def is_figure(value: Type) -> bool:
  112. """Check if the given value is a figure.
  113. Args:
  114. value: The value to check.
  115. Returns:
  116. Whether the value is a figure.
  117. """
  118. return value.__name__ == "Figure"
  119. def is_valid_var_type(var: Type) -> bool:
  120. """Check if the given value is a valid prop type.
  121. Args:
  122. var: The value to check.
  123. Returns:
  124. Whether the value is a valid prop type.
  125. """
  126. return (
  127. _issubclass(var, StateVar)
  128. or is_dataframe(var)
  129. or is_figure(var)
  130. or is_image(var)
  131. )
  132. def is_backend_variable(name: str) -> bool:
  133. """Check if this variable name correspond to a backend variable.
  134. Args:
  135. name: The name of the variable to check
  136. Returns:
  137. bool: The result of the check
  138. """
  139. return name.startswith("_") and not name.startswith("__")
  140. # Store this here for performance.
  141. StateBases = get_base_class(StateVar)