types.py 15 KB

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