types.py 13 KB

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