types.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import inspect
  5. import types
  6. from functools import wraps
  7. from typing import (
  8. Any,
  9. Callable,
  10. Iterable,
  11. List,
  12. Literal,
  13. Optional,
  14. Type,
  15. Union,
  16. _GenericAlias, # type: ignore
  17. get_args,
  18. get_origin,
  19. get_type_hints,
  20. )
  21. import sqlalchemy
  22. from sqlalchemy.ext.hybrid import hybrid_property
  23. from sqlalchemy.orm import DeclarativeBase, Mapped, QueryableAttribute, Relationship
  24. from reflex import constants
  25. from reflex.base import Base
  26. from reflex.utils import serializers
  27. # Union of generic types.
  28. GenericType = Union[Type, _GenericAlias]
  29. # Valid state var types.
  30. JSONType = {str, int, float, bool}
  31. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  32. StateVar = Union[PrimitiveType, Base, None]
  33. StateIterVar = Union[list, set, tuple]
  34. # ArgsSpec = Callable[[Var], list[Var]]
  35. ArgsSpec = Callable
  36. class Unset:
  37. """A class to represent an unset value.
  38. This is used to differentiate between a value that is not set and a value that is set to None.
  39. """
  40. def __repr__(self) -> str:
  41. """Return the string representation of the class.
  42. Returns:
  43. The string representation of the class.
  44. """
  45. return "Unset"
  46. def __bool__(self) -> bool:
  47. """Return False when the class is used in a boolean context.
  48. Returns:
  49. False
  50. """
  51. return False
  52. def is_generic_alias(cls: GenericType) -> bool:
  53. """Check whether the class is a generic alias.
  54. Args:
  55. cls: The class to check.
  56. Returns:
  57. Whether the class is a generic alias.
  58. """
  59. # For older versions of Python.
  60. if isinstance(cls, _GenericAlias):
  61. return True
  62. with contextlib.suppress(ImportError):
  63. from typing import _SpecialGenericAlias # type: ignore
  64. if isinstance(cls, _SpecialGenericAlias):
  65. return True
  66. # For newer versions of Python.
  67. try:
  68. from types import GenericAlias # type: ignore
  69. return isinstance(cls, GenericAlias)
  70. except ImportError:
  71. return False
  72. def is_union(cls: GenericType) -> bool:
  73. """Check if a class is a Union.
  74. Args:
  75. cls: The class to check.
  76. Returns:
  77. Whether the class is a Union.
  78. """
  79. # UnionType added in py3.10
  80. if not hasattr(types, "UnionType"):
  81. return get_origin(cls) is Union
  82. return get_origin(cls) in [Union, types.UnionType]
  83. def is_literal(cls: GenericType) -> bool:
  84. """Check if a class is a Literal.
  85. Args:
  86. cls: The class to check.
  87. Returns:
  88. Whether the class is a literal.
  89. """
  90. return get_origin(cls) is Literal
  91. def is_optional(cls: GenericType) -> bool:
  92. """Check if a class is an Optional.
  93. Args:
  94. cls: The class to check.
  95. Returns:
  96. Whether the class is an Optional.
  97. """
  98. return is_union(cls) and type(None) in get_args(cls)
  99. def get_property_hint(attr: Any | None) -> GenericType | None:
  100. """Check if an attribute is a property and return its type hint.
  101. Args:
  102. attr: The descriptor to check.
  103. Returns:
  104. The type hint of the property, if it is a property, else None.
  105. """
  106. if not isinstance(attr, (property, hybrid_property)):
  107. return None
  108. hints = get_type_hints(attr.fget)
  109. return hints.get("return", None)
  110. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  111. """Check if an attribute can be accessed on the cls and return its type.
  112. Supports pydantic models, unions, and annotated attributes on rx.Model.
  113. Args:
  114. cls: The class to check.
  115. name: The name of the attribute to check.
  116. Returns:
  117. The type of the attribute, if accessible, or None
  118. """
  119. from reflex.model import Model
  120. attr = getattr(cls, name, None)
  121. if hint := get_property_hint(attr):
  122. return hint
  123. if hasattr(cls, "model_fields") and name in cls.model_fields:
  124. # pydantic models
  125. field = cls.model_fields[name]
  126. type_ = field.annotation
  127. if (
  128. not field.is_required()
  129. and field.default is None
  130. and field.default_factory is None
  131. ):
  132. # Ensure frontend uses null coalescing when accessing.
  133. type_ = Optional[type_]
  134. return type_
  135. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  136. insp = sqlalchemy.inspect(cls)
  137. if name in insp.columns:
  138. return insp.columns[name].type.python_type
  139. if name not in insp.all_orm_descriptors.keys():
  140. return None
  141. descriptor = insp.all_orm_descriptors[name]
  142. if hint := get_property_hint(descriptor):
  143. return hint
  144. if isinstance(descriptor, QueryableAttribute):
  145. prop = descriptor.property
  146. if not isinstance(prop, Relationship):
  147. return None
  148. class_ = prop.mapper.class_
  149. if prop.uselist:
  150. return List[class_]
  151. else:
  152. return class_
  153. elif isinstance(cls, type) and issubclass(cls, Model):
  154. # Check in the annotations directly (for sqlmodel.Relationship)
  155. hints = get_type_hints(cls)
  156. if name in hints:
  157. type_ = hints[name]
  158. type_origin = get_origin(type_)
  159. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  160. return get_args(type_)[0] # SQLAlchemy v2
  161. # TODO: pydantic v2
  162. # if isinstance(type_, ModelField):
  163. # return type_.type_ # SQLAlchemy v1.4
  164. return type_
  165. elif is_union(cls):
  166. # Check in each arg of the annotation.
  167. for arg in get_args(cls):
  168. type_ = get_attribute_access_type(arg, name)
  169. if type_ is not None:
  170. # Return the first attribute type that is accessible.
  171. return type_
  172. return None # Attribute is not accessible.
  173. def get_base_class(cls: GenericType) -> Type:
  174. """Get the base class of a class.
  175. Args:
  176. cls: The class.
  177. Returns:
  178. The base class of the class.
  179. Raises:
  180. TypeError: If a literal has multiple types.
  181. """
  182. if is_literal(cls):
  183. # only literals of the same type are supported.
  184. arg_type = type(get_args(cls)[0])
  185. if not all(type(arg) == arg_type for arg in get_args(cls)):
  186. raise TypeError("only literals of the same type are supported")
  187. return type(get_args(cls)[0])
  188. if is_union(cls):
  189. return tuple(get_base_class(arg) for arg in get_args(cls))
  190. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  191. def _issubclass(cls: GenericType, cls_check: GenericType) -> bool:
  192. """Check if a class is a subclass of another class.
  193. Args:
  194. cls: The class to check.
  195. cls_check: The class to check against.
  196. Returns:
  197. Whether the class is a subclass of the other class.
  198. Raises:
  199. TypeError: If the base class is not valid for issubclass.
  200. """
  201. # Special check for Any.
  202. if cls_check == Any:
  203. return True
  204. if cls in [Any, Callable, None]:
  205. return False
  206. # Get the base classes.
  207. cls_base = get_base_class(cls)
  208. cls_check_base = get_base_class(cls_check)
  209. # The class we're checking should not be a union.
  210. if isinstance(cls_base, tuple):
  211. return False
  212. # Check if the types match.
  213. try:
  214. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  215. except TypeError as te:
  216. # These errors typically arise from bad annotations and are hard to
  217. # debug without knowing the type that we tried to compare.
  218. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  219. def _isinstance(obj: Any, cls: GenericType) -> bool:
  220. """Check if an object is an instance of a class.
  221. Args:
  222. obj: The object to check.
  223. cls: The class to check against.
  224. Returns:
  225. Whether the object is an instance of the class.
  226. """
  227. return isinstance(obj, get_base_class(cls))
  228. def is_dataframe(value: Type) -> bool:
  229. """Check if the given value is a dataframe.
  230. Args:
  231. value: The value to check.
  232. Returns:
  233. Whether the value is a dataframe.
  234. """
  235. if is_generic_alias(value) or value == Any:
  236. return False
  237. return value.__name__ == "DataFrame"
  238. def is_valid_var_type(type_: Type) -> bool:
  239. """Check if the given type is a valid prop type.
  240. Args:
  241. type_: The type to check.
  242. Returns:
  243. Whether the type is a valid prop type.
  244. """
  245. if is_union(type_):
  246. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  247. return _issubclass(type_, StateVar) or serializers.has_serializer(type_)
  248. def is_backend_variable(name: str, cls: Type | None = None) -> bool:
  249. """Check if this variable name correspond to a backend variable.
  250. Args:
  251. name: The name of the variable to check
  252. cls: The class of the variable to check
  253. Returns:
  254. bool: The result of the check
  255. """
  256. if cls is not None and name.startswith(f"_{cls.__name__}__"):
  257. return False
  258. return name.startswith("_") and not name.startswith("__")
  259. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  260. """Check that a value type is found in a list of allowed types.
  261. Args:
  262. value_type: Type of value.
  263. allowed_types: Iterable of allowed types.
  264. Returns:
  265. If the type is found in the allowed types.
  266. """
  267. return get_base_class(value_type) in allowed_types
  268. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  269. """Check that a prop value is in a list of allowed types.
  270. Does the check in a way that works regardless if it's a raw value or a state Var.
  271. Args:
  272. prop: The prop to check.
  273. allowed_types: The list of allowed types.
  274. Returns:
  275. If the prop type match one of the allowed_types.
  276. """
  277. from reflex.vars import Var
  278. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  279. return type_ in allowed_types
  280. def is_encoded_fstring(value) -> bool:
  281. """Check if a value is an encoded Var f-string.
  282. Args:
  283. value: The value string to check.
  284. Returns:
  285. Whether the value is an f-string
  286. """
  287. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  288. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  289. """Check that a value is a valid literal.
  290. Args:
  291. key: The prop name.
  292. value: The prop value to validate.
  293. expected_type: The expected type(literal type).
  294. comp_name: Name of the component.
  295. Raises:
  296. ValueError: When the value is not a valid literal.
  297. """
  298. from reflex.vars import Var
  299. if (
  300. is_literal(expected_type)
  301. and not isinstance(value, Var) # validating vars is not supported yet.
  302. and not is_encoded_fstring(value) # f-strings are not supported.
  303. and value not in expected_type.__args__
  304. ):
  305. allowed_values = expected_type.__args__
  306. if value not in allowed_values:
  307. value_str = ",".join(
  308. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  309. )
  310. raise ValueError(
  311. f"prop value for {str(key)} of the `{comp_name}` component should be one of the following: {value_str}. Got '{value}' instead"
  312. )
  313. def validate_parameter_literals(func):
  314. """Decorator to check that the arguments passed to a function
  315. correspond to the correct function parameter if it (the parameter)
  316. is a literal type.
  317. Args:
  318. func: The function to validate.
  319. Returns:
  320. The wrapper function.
  321. """
  322. @wraps(func)
  323. def wrapper(*args, **kwargs):
  324. func_params = list(inspect.signature(func).parameters.items())
  325. annotations = {param[0]: param[1].annotation for param in func_params}
  326. # validate args
  327. for param, arg in zip(annotations.keys(), args):
  328. if annotations[param] is inspect.Parameter.empty:
  329. continue
  330. validate_literal(param, arg, annotations[param], func.__name__)
  331. # validate kwargs.
  332. for key, value in kwargs.items():
  333. annotation = annotations.get(key)
  334. if not annotation or annotation is inspect.Parameter.empty:
  335. continue
  336. validate_literal(key, value, annotation, func.__name__)
  337. return func(*args, **kwargs)
  338. return wrapper
  339. # Store this here for performance.
  340. StateBases = get_base_class(StateVar)
  341. StateIterBases = get_base_class(StateIterVar)