types.py 12 KB

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