types.py 17 KB

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