types.py 16 KB

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